blob: 782acfa0516667be24c631fc5a807268245de671 [file] [log] [blame]
Dan Gohman91d598d2009-09-10 23:07:18 +00001//===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
John Criswell970af112005-10-27 16:00:10 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
John Criswell970af112005-10-27 16:00:10 +00007//
8//===----------------------------------------------------------------------===//
9//
Dan Gohman91d598d2009-09-10 23:07:18 +000010// This file defines routines for folding instructions into constants.
11//
Chandler Carruthef860a22013-01-02 09:10:48 +000012// Also, to supplement the basic IR ConstantExpr simplifications,
Dan Gohman91d598d2009-09-10 23:07:18 +000013// this file defines some additional folding routines that can make use of
Chandler Carruthef860a22013-01-02 09:10:48 +000014// DataLayout information. These functions cannot go in IR due to library
Dan Gohman91d598d2009-09-10 23:07:18 +000015// dependency issues.
John Criswell970af112005-10-27 16:00:10 +000016//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Analysis/ConstantFolding.h"
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +000020#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringMap.h"
23#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000028#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/GlobalVariable.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/Operator.h"
Torok Edwin56d06592009-07-11 20:10:48 +000033#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/FEnv.h"
John Criswell970af112005-10-27 16:00:10 +000035#include "llvm/Support/MathExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Target/TargetLibraryInfo.h"
John Criswell970af112005-10-27 16:00:10 +000037#include <cerrno>
Jeff Cohencc08c832006-12-02 02:22:01 +000038#include <cmath>
John Criswell970af112005-10-27 16:00:10 +000039using namespace llvm;
40
Chris Lattner44d68b92007-01-31 00:51:48 +000041//===----------------------------------------------------------------------===//
42// Constant Folding internal helper functions
43//===----------------------------------------------------------------------===//
44
NAKAMURA Takumidce89992012-11-05 00:11:11 +000045/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
Micah Villmowcdfe20b2012-10-08 16:38:25 +000046/// DataLayout. This always returns a non-null constant, but it may be a
Chris Lattner9d051242009-10-25 06:08:26 +000047/// ConstantExpr if unfoldable.
Chris Lattner229907c2011-07-18 04:54:35 +000048static Constant *FoldBitCast(Constant *C, Type *DestTy,
Micah Villmowcdfe20b2012-10-08 16:38:25 +000049 const DataLayout &TD) {
Nadav Rotem365af6f2011-08-24 20:18:38 +000050 // Catch the obvious splat cases.
51 if (C->isNullValue() && !DestTy->isX86_MMXTy())
52 return Constant::getNullValue(DestTy);
53 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy())
54 return Constant::getAllOnesValue(DestTy);
55
Rafael Espindolabb893fe2012-01-27 23:33:07 +000056 // Handle a vector->integer cast.
57 if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
Michael Ilsemana7b93c12013-02-26 22:51:07 +000058 VectorType *VTy = dyn_cast<VectorType>(C->getType());
59 if (VTy == 0)
Rafael Espindolabb893fe2012-01-27 23:33:07 +000060 return ConstantExpr::getBitCast(C, DestTy);
61
Michael Ilsemana7b93c12013-02-26 22:51:07 +000062 unsigned NumSrcElts = VTy->getNumElements();
63 Type *SrcEltTy = VTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +000064
Rafael Espindolabb893fe2012-01-27 23:33:07 +000065 // If the vector is a vector of floating point, convert it to vector of int
66 // to simplify things.
Chris Lattner8213c8a2012-02-06 21:56:39 +000067 if (SrcEltTy->isFloatingPointTy()) {
68 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Rafael Espindolabb893fe2012-01-27 23:33:07 +000069 Type *SrcIVTy =
70 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
Chandler Carruthef860a22013-01-02 09:10:48 +000071 // Ask IR to do the conversion now that #elts line up.
Rafael Espindolabb893fe2012-01-27 23:33:07 +000072 C = ConstantExpr::getBitCast(C, SrcIVTy);
73 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000074
Michael Ilsemana7b93c12013-02-26 22:51:07 +000075 ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
76 if (CDV == 0)
77 return ConstantExpr::getBitCast(C, DestTy);
78
Rafael Espindolabb893fe2012-01-27 23:33:07 +000079 // Now that we know that the input value is a vector of integers, just shift
80 // and insert them into our result.
Chris Lattner8213c8a2012-02-06 21:56:39 +000081 unsigned BitShift = TD.getTypeAllocSizeInBits(SrcEltTy);
Rafael Espindolabb893fe2012-01-27 23:33:07 +000082 APInt Result(IT->getBitWidth(), 0);
83 for (unsigned i = 0; i != NumSrcElts; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +000084 Result <<= BitShift;
85 if (TD.isLittleEndian())
86 Result |= CDV->getElementAsInteger(NumSrcElts-i-1);
87 else
88 Result |= CDV->getElementAsInteger(i);
Rafael Espindolabb893fe2012-01-27 23:33:07 +000089 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000090
Rafael Espindolabb893fe2012-01-27 23:33:07 +000091 return ConstantInt::get(IT, Result);
92 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000093
Nadav Rotemad4a70a2011-08-20 14:02:29 +000094 // The code below only handles casts to vectors currently.
Chris Lattner229907c2011-07-18 04:54:35 +000095 VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
Chris Lattnerd8e8fb42009-10-25 06:15:37 +000096 if (DestVTy == 0)
97 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +000098
Chris Lattnerd8e8fb42009-10-25 06:15:37 +000099 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
100 // vector so the code below can handle it uniformly.
101 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
102 Constant *Ops = C; // don't take the address of C!
Chris Lattner69229312011-02-15 00:14:00 +0000103 return FoldBitCast(ConstantVector::get(Ops), DestTy, TD);
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000104 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000105
Chris Lattner9d051242009-10-25 06:08:26 +0000106 // If this is a bitcast from constant vector -> vector, fold it.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000107 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000108 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000109
Chandler Carruthef860a22013-01-02 09:10:48 +0000110 // If the element types match, IR can fold it.
Chris Lattner9d051242009-10-25 06:08:26 +0000111 unsigned NumDstElt = DestVTy->getNumElements();
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000112 unsigned NumSrcElt = C->getType()->getVectorNumElements();
Chris Lattner9d051242009-10-25 06:08:26 +0000113 if (NumDstElt == NumSrcElt)
114 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000115
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000116 Type *SrcEltTy = C->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000117 Type *DstEltTy = DestVTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000118
119 // Otherwise, we're changing the number of elements in a vector, which
Chris Lattner9d051242009-10-25 06:08:26 +0000120 // requires endianness information to do the right thing. For example,
121 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
122 // folds to (little endian):
123 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
124 // and to (big endian):
125 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000126
Chris Lattner9d051242009-10-25 06:08:26 +0000127 // First thing is first. We only want to think about integer here, so if
128 // we have something in FP form, recast it as integer.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000129 if (DstEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000130 // Fold to an vector of integers with same size as our FP type.
131 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000132 Type *DestIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000133 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
134 // Recursively handle this integer conversion, if possible.
135 C = FoldBitCast(C, DestIVTy, TD);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000136
Chandler Carruthef860a22013-01-02 09:10:48 +0000137 // Finally, IR can handle this now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000138 return ConstantExpr::getBitCast(C, DestTy);
139 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000140
Chris Lattner9d051242009-10-25 06:08:26 +0000141 // Okay, we know the destination is integer, if the input is FP, convert
142 // it to integer first.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000143 if (SrcEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000144 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000145 Type *SrcIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000146 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
Chandler Carruthef860a22013-01-02 09:10:48 +0000147 // Ask IR to do the conversion now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000148 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chandler Carruthef860a22013-01-02 09:10:48 +0000149 // If IR wasn't able to fold it, bail out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000150 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
151 !isa<ConstantDataVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000152 return C;
153 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000154
Chris Lattner9d051242009-10-25 06:08:26 +0000155 // Now we know that the input and output vectors are both integer vectors
156 // of the same size, and that their #elements is not the same. Do the
157 // conversion here, which depends on whether the input or output has
158 // more elements.
159 bool isLittleEndian = TD.isLittleEndian();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000160
Chris Lattner9d051242009-10-25 06:08:26 +0000161 SmallVector<Constant*, 32> Result;
162 if (NumDstElt < NumSrcElt) {
163 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
164 Constant *Zero = Constant::getNullValue(DstEltTy);
165 unsigned Ratio = NumSrcElt/NumDstElt;
166 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
167 unsigned SrcElt = 0;
168 for (unsigned i = 0; i != NumDstElt; ++i) {
169 // Build each element of the result.
170 Constant *Elt = Zero;
171 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
172 for (unsigned j = 0; j != Ratio; ++j) {
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000173 Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
Chris Lattner9d051242009-10-25 06:08:26 +0000174 if (!Src) // Reject constantexpr elements.
175 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000176
Chris Lattner9d051242009-10-25 06:08:26 +0000177 // Zero extend the element to the right size.
178 Src = ConstantExpr::getZExt(Src, Elt->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000179
Chris Lattner9d051242009-10-25 06:08:26 +0000180 // Shift it to the right place, depending on endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000181 Src = ConstantExpr::getShl(Src,
Chris Lattner9d051242009-10-25 06:08:26 +0000182 ConstantInt::get(Src->getType(), ShiftAmt));
183 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000184
Chris Lattner9d051242009-10-25 06:08:26 +0000185 // Mix it in.
186 Elt = ConstantExpr::getOr(Elt, Src);
187 }
188 Result.push_back(Elt);
189 }
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000190 return ConstantVector::get(Result);
191 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000192
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000193 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
194 unsigned Ratio = NumDstElt/NumSrcElt;
195 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000196
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000197 // Loop over each source value, expanding into multiple results.
198 for (unsigned i = 0; i != NumSrcElt; ++i) {
199 Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
200 if (!Src) // Reject constantexpr elements.
201 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000202
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000203 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
204 for (unsigned j = 0; j != Ratio; ++j) {
205 // Shift the piece of the value into the right place, depending on
206 // endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000207 Constant *Elt = ConstantExpr::getLShr(Src,
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000208 ConstantInt::get(Src->getType(), ShiftAmt));
209 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000210
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000211 // Truncate and remember this piece.
212 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner9d051242009-10-25 06:08:26 +0000213 }
214 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000215
Chris Lattner69229312011-02-15 00:14:00 +0000216 return ConstantVector::get(Result);
Chris Lattner9d051242009-10-25 06:08:26 +0000217}
218
219
Chris Lattner44d68b92007-01-31 00:51:48 +0000220/// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
221/// from a global, return the global and the constant. Because of
222/// constantexprs, this function is recursive.
223static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
Benjamin Kramer546bb562013-01-23 21:21:24 +0000224 APInt &Offset, const DataLayout &TD) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000225 // Trivial case, constant is the global.
226 if ((GV = dyn_cast<GlobalValue>(C))) {
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000227 unsigned BitWidth = TD.getPointerTypeSizeInBits(GV->getType());
228 Offset = APInt(BitWidth, 0);
Chris Lattner44d68b92007-01-31 00:51:48 +0000229 return true;
230 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000231
Chris Lattner44d68b92007-01-31 00:51:48 +0000232 // Otherwise, if this isn't a constant expr, bail out.
233 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
234 if (!CE) return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000235
Chris Lattner44d68b92007-01-31 00:51:48 +0000236 // Look through ptr->int and ptr->ptr casts.
237 if (CE->getOpcode() == Instruction::PtrToInt ||
238 CE->getOpcode() == Instruction::BitCast)
239 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000240
241 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000242 GEPOperator *GEP = dyn_cast<GEPOperator>(CE);
243 if (!GEP)
244 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000245
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000246 unsigned BitWidth = TD.getPointerTypeSizeInBits(GEP->getType());
247 APInt TmpOffset(BitWidth, 0);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000248
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000249 // If the base isn't a global+constant, we aren't either.
250 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, TD))
251 return false;
252
253 // Otherwise, add any offset that our operands provide.
254 if (!GEP->accumulateConstantOffset(TD, TmpOffset))
255 return false;
256
257 Offset = TmpOffset;
258 return true;
Chris Lattner44d68b92007-01-31 00:51:48 +0000259}
260
Chris Lattnered00b802009-10-23 06:23:49 +0000261/// ReadDataFromGlobal - Recursive helper to read bits out of global. C is the
262/// constant being copied out of. ByteOffset is an offset into C. CurPtr is the
263/// pointer to copy results into and BytesLeft is the number of bytes left in
264/// the CurPtr buffer. TD is the target data.
265static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
266 unsigned char *CurPtr, unsigned BytesLeft,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000267 const DataLayout &TD) {
Chris Lattnered00b802009-10-23 06:23:49 +0000268 assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
269 "Out of range access");
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000270
Chris Lattner3db7bd22009-10-24 05:27:19 +0000271 // If this element is zero or undefined, we can just return since *CurPtr is
272 // zero initialized.
Chris Lattnered00b802009-10-23 06:23:49 +0000273 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
274 return true;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000275
Chris Lattnered00b802009-10-23 06:23:49 +0000276 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
277 if (CI->getBitWidth() > 64 ||
278 (CI->getBitWidth() & 7) != 0)
279 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000280
Chris Lattnered00b802009-10-23 06:23:49 +0000281 uint64_t Val = CI->getZExtValue();
282 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000283
Chris Lattnered00b802009-10-23 06:23:49 +0000284 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000285 int n = ByteOffset;
286 if (!TD.isLittleEndian())
287 n = IntBytes - n - 1;
288 CurPtr[i] = (unsigned char)(Val >> (n * 8));
Chris Lattnered00b802009-10-23 06:23:49 +0000289 ++ByteOffset;
290 }
291 return true;
292 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000293
Chris Lattnered00b802009-10-23 06:23:49 +0000294 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
295 if (CFP->getType()->isDoubleTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000296 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000297 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
298 }
299 if (CFP->getType()->isFloatTy()){
Chris Lattner9d051242009-10-25 06:08:26 +0000300 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000301 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
302 }
Owen Andersond4ebfd82013-02-06 22:43:31 +0000303 if (CFP->getType()->isHalfTy()){
304 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), TD);
305 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
306 }
Chris Lattner3db7bd22009-10-24 05:27:19 +0000307 return false;
Chris Lattnered00b802009-10-23 06:23:49 +0000308 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000309
Chris Lattnered00b802009-10-23 06:23:49 +0000310 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
311 const StructLayout *SL = TD.getStructLayout(CS->getType());
312 unsigned Index = SL->getElementContainingOffset(ByteOffset);
313 uint64_t CurEltOffset = SL->getElementOffset(Index);
314 ByteOffset -= CurEltOffset;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000315
Chris Lattnered00b802009-10-23 06:23:49 +0000316 while (1) {
317 // If the element access is to the element itself and not to tail padding,
318 // read the bytes from the element.
319 uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
320
321 if (ByteOffset < EltSize &&
322 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
323 BytesLeft, TD))
324 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000325
Chris Lattnered00b802009-10-23 06:23:49 +0000326 ++Index;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000327
Chris Lattnered00b802009-10-23 06:23:49 +0000328 // Check to see if we read from the last struct element, if so we're done.
329 if (Index == CS->getType()->getNumElements())
330 return true;
331
332 // If we read all of the bytes we needed from this element we're done.
333 uint64_t NextEltOffset = SL->getElementOffset(Index);
334
Matt Arsenault8c789092013-08-12 23:15:58 +0000335 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
Chris Lattnered00b802009-10-23 06:23:49 +0000336 return true;
337
338 // Move to the next element of the struct.
Matt Arsenault8c789092013-08-12 23:15:58 +0000339 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
340 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
Chris Lattnered00b802009-10-23 06:23:49 +0000341 ByteOffset = 0;
342 CurEltOffset = NextEltOffset;
343 }
344 // not reached.
345 }
346
Chris Lattner67058832012-01-25 06:48:06 +0000347 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
348 isa<ConstantDataSequential>(C)) {
Matt Arsenault8c789092013-08-12 23:15:58 +0000349 Type *EltTy = C->getType()->getSequentialElementType();
Chris Lattner67058832012-01-25 06:48:06 +0000350 uint64_t EltSize = TD.getTypeAllocSize(EltTy);
Chris Lattnered00b802009-10-23 06:23:49 +0000351 uint64_t Index = ByteOffset / EltSize;
352 uint64_t Offset = ByteOffset - Index * EltSize;
Chris Lattner67058832012-01-25 06:48:06 +0000353 uint64_t NumElts;
354 if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
355 NumElts = AT->getNumElements();
356 else
Matt Arsenault8c789092013-08-12 23:15:58 +0000357 NumElts = C->getType()->getVectorNumElements();
Duncan Sands0b875a02012-07-25 09:14:54 +0000358
Chris Lattner67058832012-01-25 06:48:06 +0000359 for (; Index != NumElts; ++Index) {
360 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
361 BytesLeft, TD))
362 return false;
Duncan Sands0b875a02012-07-25 09:14:54 +0000363
364 uint64_t BytesWritten = EltSize - Offset;
365 assert(BytesWritten <= EltSize && "Not indexing into this element?");
366 if (BytesWritten >= BytesLeft)
Chris Lattner67058832012-01-25 06:48:06 +0000367 return true;
Duncan Sands0b875a02012-07-25 09:14:54 +0000368
Chris Lattner67058832012-01-25 06:48:06 +0000369 Offset = 0;
Duncan Sands0b875a02012-07-25 09:14:54 +0000370 BytesLeft -= BytesWritten;
371 CurPtr += BytesWritten;
Chris Lattner67058832012-01-25 06:48:06 +0000372 }
373 return true;
374 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000375
Anders Carlssond21b06a2011-02-06 20:11:56 +0000376 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Anders Carlssonecf8e152011-02-06 20:22:49 +0000377 if (CE->getOpcode() == Instruction::IntToPtr &&
Matt Arsenault7a960a82013-08-20 21:20:04 +0000378 CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getType())) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000379 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
Chris Lattner67058832012-01-25 06:48:06 +0000380 BytesLeft, TD);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000381 }
Anders Carlssond21b06a2011-02-06 20:11:56 +0000382 }
383
Chris Lattnered00b802009-10-23 06:23:49 +0000384 // Otherwise, unknown initializer type.
385 return false;
386}
387
388static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000389 const DataLayout &TD) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000390 PointerType *PTy = cast<PointerType>(C->getType());
391 Type *LoadTy = PTy->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000392 IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000393
Chris Lattnered00b802009-10-23 06:23:49 +0000394 // If this isn't an integer load we can't fold it directly.
395 if (!IntType) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000396 unsigned AS = PTy->getAddressSpace();
397
Chris Lattnered00b802009-10-23 06:23:49 +0000398 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattnerccf1e842009-10-23 06:57:37 +0000399 // and then bitcast the result. This can be useful for union cases. Note
400 // that address spaces don't matter here since we're not going to result in
401 // an actual new load.
Chris Lattner229907c2011-07-18 04:54:35 +0000402 Type *MapTy;
Owen Andersond4ebfd82013-02-06 22:43:31 +0000403 if (LoadTy->isHalfTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000404 MapTy = Type::getInt16PtrTy(C->getContext(), AS);
Owen Andersond4ebfd82013-02-06 22:43:31 +0000405 else if (LoadTy->isFloatTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000406 MapTy = Type::getInt32PtrTy(C->getContext(), AS);
Chris Lattnerccf1e842009-10-23 06:57:37 +0000407 else if (LoadTy->isDoubleTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000408 MapTy = Type::getInt64PtrTy(C->getContext(), AS);
Duncan Sands19d0b472010-02-16 11:11:14 +0000409 else if (LoadTy->isVectorTy()) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000410 MapTy = PointerType::getIntNPtrTy(C->getContext(),
411 TD.getTypeAllocSizeInBits(LoadTy),
412 AS);
Chris Lattnerccf1e842009-10-23 06:57:37 +0000413 } else
Chris Lattnered00b802009-10-23 06:23:49 +0000414 return 0;
415
Chris Lattner9d051242009-10-25 06:08:26 +0000416 C = FoldBitCast(C, MapTy, TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000417 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
Chris Lattner9d051242009-10-25 06:08:26 +0000418 return FoldBitCast(Res, LoadTy, TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000419 return 0;
420 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000421
Chris Lattnered00b802009-10-23 06:23:49 +0000422 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Matt Arsenault8c789092013-08-12 23:15:58 +0000423 if (BytesLoaded > 32 || BytesLoaded == 0)
424 return 0;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000425
Chris Lattnered00b802009-10-23 06:23:49 +0000426 GlobalValue *GVal;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000427 APInt Offset;
Chris Lattnered00b802009-10-23 06:23:49 +0000428 if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
429 return 0;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000430
Chris Lattnered00b802009-10-23 06:23:49 +0000431 GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattner3db7bd22009-10-24 05:27:19 +0000432 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnered00b802009-10-23 06:23:49 +0000433 !GV->getInitializer()->getType()->isSized())
434 return 0;
435
436 // If we're loading off the beginning of the global, some bytes may be valid,
437 // but we don't try to handle this.
Matt Arsenault8c789092013-08-12 23:15:58 +0000438 if (Offset.isNegative())
439 return 0;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000440
Chris Lattnered00b802009-10-23 06:23:49 +0000441 // If we're not accessing anything in this constant, the result is undefined.
Benjamin Kramer546bb562013-01-23 21:21:24 +0000442 if (Offset.getZExtValue() >=
443 TD.getTypeAllocSize(GV->getInitializer()->getType()))
Chris Lattnered00b802009-10-23 06:23:49 +0000444 return UndefValue::get(IntType);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000445
Chris Lattner59f94c02009-10-23 06:50:36 +0000446 unsigned char RawBytes[32] = {0};
Benjamin Kramer546bb562013-01-23 21:21:24 +0000447 if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
Chris Lattnered00b802009-10-23 06:23:49 +0000448 BytesLoaded, TD))
449 return 0;
450
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000451 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
452 if (TD.isLittleEndian()) {
453 ResultVal = RawBytes[BytesLoaded - 1];
454 for (unsigned i = 1; i != BytesLoaded; ++i) {
455 ResultVal <<= 8;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000456 ResultVal |= RawBytes[BytesLoaded - 1 - i];
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000457 }
458 } else {
459 ResultVal = RawBytes[0];
460 for (unsigned i = 1; i != BytesLoaded; ++i) {
461 ResultVal <<= 8;
462 ResultVal |= RawBytes[i];
463 }
Chris Lattner59f94c02009-10-23 06:50:36 +0000464 }
Chris Lattnered00b802009-10-23 06:23:49 +0000465
Chris Lattner59f94c02009-10-23 06:50:36 +0000466 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnered00b802009-10-23 06:23:49 +0000467}
468
Chris Lattner1664a4f2009-10-22 06:25:11 +0000469/// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
470/// produce if it is constant and determinable. If this is not determinable,
471/// return null.
472Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000473 const DataLayout *TD) {
Chris Lattner1664a4f2009-10-22 06:25:11 +0000474 // First, try the easy cases:
475 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
476 if (GV->isConstant() && GV->hasDefinitiveInitializer())
477 return GV->getInitializer();
478
Chris Lattnercf7e8942009-10-22 06:44:07 +0000479 // If the loaded value isn't a constant expr, we can't handle it.
480 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000481 if (!CE)
482 return 0;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000483
Chris Lattnercf7e8942009-10-22 06:44:07 +0000484 if (CE->getOpcode() == Instruction::GetElementPtr) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000485 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
486 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000487 if (Constant *V =
Chris Lattnercf7e8942009-10-22 06:44:07 +0000488 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
489 return V;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000490 }
491 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000492 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000493
Chris Lattnercf7e8942009-10-22 06:44:07 +0000494 // Instead of loading constant c string, use corresponding integer value
495 // directly if string length is small enough.
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000496 StringRef Str;
497 if (TD && getConstantStringInfo(CE, Str) && !Str.empty()) {
498 unsigned StrLen = Str.size();
Chris Lattner229907c2011-07-18 04:54:35 +0000499 Type *Ty = cast<PointerType>(CE->getType())->getElementType();
Chris Lattnered00b802009-10-23 06:23:49 +0000500 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000501 // Replace load with immediate integer if the result is an integer or fp
502 // value.
503 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
Chandler Carruth57041d82010-07-12 06:47:05 +0000504 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
Chris Lattnered00b802009-10-23 06:23:49 +0000505 APInt StrVal(NumBits, 0);
506 APInt SingleChar(NumBits, 0);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000507 if (TD->isLittleEndian()) {
Chris Lattnered00b802009-10-23 06:23:49 +0000508 for (signed i = StrLen-1; i >= 0; i--) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000509 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Chris Lattner51d2f702009-10-22 06:38:35 +0000510 StrVal = (StrVal << 8) | SingleChar;
511 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000512 } else {
Chris Lattnered00b802009-10-23 06:23:49 +0000513 for (unsigned i = 0; i < StrLen; i++) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000514 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
515 StrVal = (StrVal << 8) | SingleChar;
516 }
517 // Append NULL at the end.
518 SingleChar = 0;
519 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner51d2f702009-10-22 06:38:35 +0000520 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000521
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000522 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
523 if (Ty->isFloatingPointTy())
524 Res = ConstantExpr::getBitCast(Res, Ty);
525 return Res;
Chris Lattner51d2f702009-10-22 06:38:35 +0000526 }
Chris Lattner1664a4f2009-10-22 06:25:11 +0000527 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000528
Chris Lattnercf7e8942009-10-22 06:44:07 +0000529 // If this load comes from anywhere in a constant global, and if the global
530 // is all undef or zero, we know what it loads.
Dan Gohman0f124e12011-01-24 18:53:32 +0000531 if (GlobalVariable *GV =
532 dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000533 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000534 Type *ResTy = cast<PointerType>(C->getType())->getElementType();
Chris Lattnercf7e8942009-10-22 06:44:07 +0000535 if (GV->getInitializer()->isNullValue())
536 return Constant::getNullValue(ResTy);
537 if (isa<UndefValue>(GV->getInitializer()))
538 return UndefValue::get(ResTy);
539 }
540 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000541
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000542 // Try hard to fold loads from bitcasted strange and non-type-safe things.
543 if (TD)
Chris Lattnered00b802009-10-23 06:23:49 +0000544 return FoldReinterpretLoadFromConstPtr(CE, *TD);
Chris Lattner1664a4f2009-10-22 06:25:11 +0000545 return 0;
546}
547
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000548static Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout *TD){
Chris Lattner1664a4f2009-10-22 06:25:11 +0000549 if (LI->isVolatile()) return 0;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000550
Chris Lattner1664a4f2009-10-22 06:25:11 +0000551 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
552 return ConstantFoldLoadFromConstPtr(C, TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000553
Chris Lattner1664a4f2009-10-22 06:25:11 +0000554 return 0;
555}
Chris Lattner44d68b92007-01-31 00:51:48 +0000556
557/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
Nick Lewyckye88d3882008-12-15 01:35:36 +0000558/// Attempt to symbolically evaluate the result of a binary operator merging
Nick Lewycky06417742013-02-14 03:23:37 +0000559/// these together. If target data info is available, it is provided as DL,
560/// otherwise DL is null.
Chris Lattner44d68b92007-01-31 00:51:48 +0000561static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
Nick Lewycky06417742013-02-14 03:23:37 +0000562 Constant *Op1, const DataLayout *DL){
Chris Lattner44d68b92007-01-31 00:51:48 +0000563 // SROA
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000564
Chris Lattner44d68b92007-01-31 00:51:48 +0000565 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
566 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
567 // bits.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000568
569
Nick Lewycky06417742013-02-14 03:23:37 +0000570 if (Opc == Instruction::And && DL) {
Benjamin Kramerec1bb4f2013-04-19 16:56:24 +0000571 unsigned BitWidth = DL->getTypeSizeInBits(Op0->getType()->getScalarType());
Nick Lewycky06417742013-02-14 03:23:37 +0000572 APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
573 APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
574 ComputeMaskedBits(Op0, KnownZero0, KnownOne0, DL);
575 ComputeMaskedBits(Op1, KnownZero1, KnownOne1, DL);
576 if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
577 // All the bits of Op0 that the 'and' could be masking are already zero.
578 return Op0;
579 }
580 if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
581 // All the bits of Op1 that the 'and' could be masking are already zero.
582 return Op1;
583 }
584
585 APInt KnownZero = KnownZero0 | KnownZero1;
586 APInt KnownOne = KnownOne0 & KnownOne1;
587 if ((KnownZero | KnownOne).isAllOnesValue()) {
588 return ConstantInt::get(Op0->getType(), KnownOne);
589 }
590 }
591
Chris Lattner44d68b92007-01-31 00:51:48 +0000592 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
593 // constant. This happens frequently when iterating over a global array.
Nick Lewycky06417742013-02-14 03:23:37 +0000594 if (Opc == Instruction::Sub && DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000595 GlobalValue *GV1, *GV2;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000596 APInt Offs1, Offs2;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000597
Nick Lewycky06417742013-02-14 03:23:37 +0000598 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *DL))
599 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *DL) &&
Chris Lattner44d68b92007-01-31 00:51:48 +0000600 GV1 == GV2) {
Matt Arsenaultbed5bf22013-09-12 01:07:58 +0000601 unsigned OpSize = DL->getTypeSizeInBits(Op0->getType());
602
Chris Lattner44d68b92007-01-31 00:51:48 +0000603 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Benjamin Kramera5a9ec52013-02-05 19:04:36 +0000604 // PtrToInt may change the bitwidth so we have convert to the right size
605 // first.
606 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
607 Offs2.zextOrTrunc(OpSize));
Chris Lattner44d68b92007-01-31 00:51:48 +0000608 }
609 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000610
Chris Lattner44d68b92007-01-31 00:51:48 +0000611 return 0;
612}
613
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000614/// CastGEPIndices - If array indices are not pointer-sized integers,
615/// explicitly cast them so that they aren't implicitly casted by the
616/// getelementptr.
Jay Foadf4b14a22011-07-19 13:32:40 +0000617static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000618 Type *ResultTy, const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000619 const TargetLibraryInfo *TLI) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000620 if (!TD)
621 return 0;
622
623 Type *IntPtrTy = TD->getIntPtrType(ResultTy);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000624
625 bool Any = false;
626 SmallVector<Constant*, 32> NewIdxs;
Jay Foadf4b14a22011-07-19 13:32:40 +0000627 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000628 if ((i == 1 ||
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000629 !isa<StructType>(GetElementPtrInst::getIndexedType(
630 Ops[0]->getType(),
631 Ops.slice(1, i - 1)))) &&
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000632 Ops[i]->getType() != IntPtrTy) {
633 Any = true;
634 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
635 true,
636 IntPtrTy,
637 true),
638 Ops[i], IntPtrTy));
639 } else
640 NewIdxs.push_back(Ops[i]);
641 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000642
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000643 if (!Any)
644 return 0;
645
646 Constant *C = ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
647 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chad Rosierc24b86f2011-12-01 03:08:23 +0000648 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD, TLI))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000649 C = Folded;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000650 }
651
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000652 return C;
653}
654
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000655/// Strip the pointer casts, but preserve the address space information.
656static Constant* StripPtrCastKeepAS(Constant* Ptr) {
657 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
658 PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
659 Ptr = cast<Constant>(Ptr->stripPointerCasts());
660 PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
661
662 // Preserve the address space number of the pointer.
663 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
664 NewPtrTy = NewPtrTy->getElementType()->getPointerTo(
665 OldPtrTy->getAddressSpace());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000666 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000667 }
668 return Ptr;
669}
670
Chris Lattner44d68b92007-01-31 00:51:48 +0000671/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
672/// constant expression, do so.
Jay Foadf4b14a22011-07-19 13:32:40 +0000673static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000674 Type *ResultTy, const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000675 const TargetLibraryInfo *TLI) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000676 Constant *Ptr = Ops[0];
Matt Arsenault8c789092013-08-12 23:15:58 +0000677 if (!TD || !Ptr->getType()->getPointerElementType()->isSized() ||
Nadav Rotem3924cb02011-12-05 06:29:09 +0000678 !Ptr->getType()->isPointerTy())
Chris Lattner44d68b92007-01-31 00:51:48 +0000679 return 0;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000680
Matt Arsenault7a960a82013-08-20 21:20:04 +0000681 Type *IntPtrTy = TD->getIntPtrType(Ptr->getType());
Matt Arsenault8c789092013-08-12 23:15:58 +0000682 Type *ResultElementTy = ResultTy->getPointerElementType();
Chris Lattnerf4b42f52008-05-08 04:54:43 +0000683
684 // If this is a constant expr gep that is effectively computing an
685 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
Jay Foadf4b14a22011-07-19 13:32:40 +0000686 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Chris Lattner5858e092011-01-06 06:19:46 +0000687 if (!isa<ConstantInt>(Ops[i])) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000688
Chris Lattner5858e092011-01-06 06:19:46 +0000689 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
690 // "inttoptr (sub (ptrtoint Ptr), V)"
Matt Arsenault8c789092013-08-12 23:15:58 +0000691 if (Ops.size() == 2 && ResultElementTy->isIntegerTy(8)) {
Chris Lattner5858e092011-01-06 06:19:46 +0000692 ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
Chris Lattner08f43452011-01-16 03:43:53 +0000693 assert((CE == 0 || CE->getType() == IntPtrTy) &&
Chris Lattner171608e2011-01-06 22:24:29 +0000694 "CastGEPIndices didn't canonicalize index types!");
Chris Lattner5858e092011-01-06 06:19:46 +0000695 if (CE && CE->getOpcode() == Instruction::Sub &&
Chris Lattner171608e2011-01-06 22:24:29 +0000696 CE->getOperand(0)->isNullValue()) {
Chris Lattner5858e092011-01-06 06:19:46 +0000697 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
698 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
699 Res = ConstantExpr::getIntToPtr(Res, ResultTy);
700 if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
Chad Rosierc24b86f2011-12-01 03:08:23 +0000701 Res = ConstantFoldConstantExpression(ResCE, TD, TLI);
Chris Lattner5858e092011-01-06 06:19:46 +0000702 return Res;
703 }
704 }
Dan Gohman81ce8422009-08-19 18:18:36 +0000705 return 0;
Chris Lattner5858e092011-01-06 06:19:46 +0000706 }
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000707
Chris Lattner171608e2011-01-06 22:24:29 +0000708 unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
Jay Foadbf904772011-07-19 14:01:37 +0000709 APInt Offset =
710 APInt(BitWidth, TD->getIndexedOffset(Ptr->getType(),
Roman Divacky4717a8d2012-09-06 15:42:13 +0000711 makeArrayRef((Value *const*)
712 Ops.data() + 1,
Jay Foadbf904772011-07-19 14:01:37 +0000713 Ops.size() - 1)));
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000714 Ptr = StripPtrCastKeepAS(Ptr);
Dan Gohman474e488c2010-03-10 19:31:51 +0000715
716 // If this is a GEP of a GEP, fold it all into a single GEP.
717 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000718 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
Duncan Sands8c355062010-03-12 17:55:20 +0000719
720 // Do not try the incorporate the sub-GEP if some index is not a number.
721 bool AllConstantInt = true;
722 for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
723 if (!isa<ConstantInt>(NestedOps[i])) {
724 AllConstantInt = false;
725 break;
726 }
727 if (!AllConstantInt)
728 break;
729
Dan Gohman474e488c2010-03-10 19:31:51 +0000730 Ptr = cast<Constant>(GEP->getOperand(0));
731 Offset += APInt(BitWidth,
Jay Foadbf904772011-07-19 14:01:37 +0000732 TD->getIndexedOffset(Ptr->getType(), NestedOps));
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000733 Ptr = StripPtrCastKeepAS(Ptr);
Dan Gohman474e488c2010-03-10 19:31:51 +0000734 }
735
Dan Gohman81ce8422009-08-19 18:18:36 +0000736 // If the base value for this address is a literal integer value, fold the
737 // getelementptr to the resulting integer value casted to the pointer type.
Dan Gohmana5ca5782010-03-18 19:34:33 +0000738 APInt BasePtr(BitWidth, 0);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000739 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
740 if (CE->getOpcode() == Instruction::IntToPtr) {
Jay Foad583abbc2010-12-07 08:25:19 +0000741 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
742 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000743 }
744 }
745
Dan Gohmana5ca5782010-03-18 19:34:33 +0000746 if (Ptr->isNullValue() || BasePtr != 0) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000747 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
Dan Gohman81ce8422009-08-19 18:18:36 +0000748 return ConstantExpr::getIntToPtr(C, ResultTy);
749 }
750
751 // Otherwise form a regular getelementptr. Recompute the indices so that
752 // we eliminate over-indexing of the notional static type array bounds.
753 // This makes it easy to determine if the getelementptr is "inbounds".
754 // Also, this helps GlobalOpt do SROA on GlobalVariables.
Chris Lattner229907c2011-07-18 04:54:35 +0000755 Type *Ty = Ptr->getType();
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000756 assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
Matt Arsenault7a960a82013-08-20 21:20:04 +0000757 SmallVector<Constant *, 32> NewIdxs;
758
Dan Gohmanc59ba422009-08-19 22:46:59 +0000759 do {
Chris Lattner229907c2011-07-18 04:54:35 +0000760 if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000761 if (ATy->isPointerTy()) {
Chris Lattner77c36d62009-12-03 01:05:45 +0000762 // The only pointer indexing we'll do is on the first index of the GEP.
763 if (!NewIdxs.empty())
764 break;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000765
Chris Lattner77c36d62009-12-03 01:05:45 +0000766 // Only handle pointers to sized types, not pointers to functions.
767 if (!ATy->getElementType()->isSized())
768 return 0;
769 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000770
Dan Gohman81ce8422009-08-19 18:18:36 +0000771 // Determine which element of the array the offset points into.
Dan Gohman23e62c52009-08-21 16:52:54 +0000772 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
Dan Gohman81ce8422009-08-19 18:18:36 +0000773 if (ElemSize == 0)
Chris Lattner6ce03802010-11-21 08:39:01 +0000774 // The element size is 0. This may be [0 x Ty]*, so just use a zero
Duncan Sands1f86be92010-11-21 12:43:13 +0000775 // index for this level and proceed to the next level to see if it can
776 // accommodate the offset.
Chris Lattner6ce03802010-11-21 08:39:01 +0000777 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
778 else {
779 // The element size is non-zero divide the offset by the element
780 // size (rounding down), to compute the index at this level.
781 APInt NewIdx = Offset.udiv(ElemSize);
782 Offset -= NewIdx * ElemSize;
783 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
784 }
Dan Gohman81ce8422009-08-19 18:18:36 +0000785 Ty = ATy->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000786 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000787 // If we end up with an offset that isn't valid for this struct type, we
788 // can't re-form this GEP in a regular form, so bail out. The pointer
789 // operand likely went through casts that are necessary to make the GEP
790 // sensible.
Dan Gohman81ce8422009-08-19 18:18:36 +0000791 const StructLayout &SL = *TD->getStructLayout(STy);
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000792 if (Offset.uge(SL.getSizeInBytes()))
793 break;
794
795 // Determine which field of the struct the offset points into. The
796 // getZExtValue is fine as we've already ensured that the offset is
797 // within the range representable by the StructLayout API.
Dan Gohman23e62c52009-08-21 16:52:54 +0000798 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Chris Lattner46b5c642009-11-06 04:27:31 +0000799 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
800 ElIdx));
Dan Gohman23e62c52009-08-21 16:52:54 +0000801 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohman81ce8422009-08-19 18:18:36 +0000802 Ty = STy->getTypeAtIndex(ElIdx);
803 } else {
Dan Gohmanc59ba422009-08-19 22:46:59 +0000804 // We've reached some non-indexable type.
805 break;
Dan Gohman81ce8422009-08-19 18:18:36 +0000806 }
Matt Arsenault8c789092013-08-12 23:15:58 +0000807 } while (Ty != ResultElementTy);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000808
809 // If we haven't used up the entire offset by descending the static
810 // type, then the offset is pointing into the middle of an indivisible
811 // member, so we can't simplify it.
812 if (Offset != 0)
813 return 0;
Dan Gohman81ce8422009-08-19 18:18:36 +0000814
Dan Gohman21c62162009-09-11 00:04:14 +0000815 // Create a GEP.
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000816 Constant *C = ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
Matt Arsenault8c789092013-08-12 23:15:58 +0000817 assert(C->getType()->getPointerElementType() == Ty &&
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000818 "Computed GetElementPtr has unexpected type!");
Dan Gohman81ce8422009-08-19 18:18:36 +0000819
Dan Gohmanc59ba422009-08-19 22:46:59 +0000820 // If we ended up indexing a member with a type that doesn't match
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000821 // the type of what the original indices indexed, add a cast.
Matt Arsenault8c789092013-08-12 23:15:58 +0000822 if (Ty != ResultElementTy)
Chris Lattner9d051242009-10-25 06:08:26 +0000823 C = FoldBitCast(C, ResultTy, *TD);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000824
825 return C;
Chris Lattner44d68b92007-01-31 00:51:48 +0000826}
827
Chris Lattner6a6b3fb2007-12-11 07:29:44 +0000828
Chris Lattner44d68b92007-01-31 00:51:48 +0000829
830//===----------------------------------------------------------------------===//
831// Constant Folding public APIs
832//===----------------------------------------------------------------------===//
833
Duncan Sands763dec02010-11-23 10:16:18 +0000834/// ConstantFoldInstruction - Try to constant fold the specified instruction.
835/// If successful, the constant result is returned, if not, null is returned.
836/// Note that this fails if not all of the operands are constant. Otherwise,
837/// this function can only fail when attempting to fold instructions like loads
838/// and stores, which have no constant expression form.
Chad Rosierc24b86f2011-12-01 03:08:23 +0000839Constant *llvm::ConstantFoldInstruction(Instruction *I,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000840 const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000841 const TargetLibraryInfo *TLI) {
Duncan Sands763dec02010-11-23 10:16:18 +0000842 // Handle PHI nodes quickly here...
Chris Lattner2ae054a2007-01-30 23:45:45 +0000843 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Duncan Sands1d27f0122010-11-14 12:53:18 +0000844 Constant *CommonValue = 0;
John Criswell970af112005-10-27 16:00:10 +0000845
Duncan Sands1d27f0122010-11-14 12:53:18 +0000846 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
847 Value *Incoming = PN->getIncomingValue(i);
Duncan Sands763dec02010-11-23 10:16:18 +0000848 // If the incoming value is undef then skip it. Note that while we could
849 // skip the value if it is equal to the phi node itself we choose not to
850 // because that would break the rule that constant folding only applies if
851 // all operands are constants.
852 if (isa<UndefValue>(Incoming))
Duncan Sands1d27f0122010-11-14 12:53:18 +0000853 continue;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000854 // If the incoming value is not a constant, then give up.
Duncan Sands1d27f0122010-11-14 12:53:18 +0000855 Constant *C = dyn_cast<Constant>(Incoming);
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000856 if (!C)
857 return 0;
858 // Fold the PHI's operands.
859 if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
860 C = ConstantFoldConstantExpression(NewC, TD, TLI);
861 // If the incoming value is a different constant to
862 // the one we saw previously, then give up.
863 if (CommonValue && C != CommonValue)
Duncan Sands1d27f0122010-11-14 12:53:18 +0000864 return 0;
865 CommonValue = C;
866 }
Chris Lattner2ae054a2007-01-30 23:45:45 +0000867
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000868
Duncan Sands1d27f0122010-11-14 12:53:18 +0000869 // If we reach here, all incoming values are the same constant or undef.
870 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
Chris Lattner2ae054a2007-01-30 23:45:45 +0000871 }
872
873 // Scan the operand list, checking to see if they are all constants, if so,
874 // hand off to ConstantFoldInstOperands.
875 SmallVector<Constant*, 8> Ops;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000876 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
877 Constant *Op = dyn_cast<Constant>(*i);
878 if (!Op)
Chris Lattner2ae054a2007-01-30 23:45:45 +0000879 return 0; // All operands not constant!
880
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000881 // Fold the Instruction's operands.
882 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
883 Op = ConstantFoldConstantExpression(NewCE, TD, TLI);
884
885 Ops.push_back(Op);
886 }
887
Chris Lattnerd2265b42007-12-10 22:53:04 +0000888 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +0000889 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
Chad Rosierc24b86f2011-12-01 03:08:23 +0000890 TD, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000891
Chris Lattner1664a4f2009-10-22 06:25:11 +0000892 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
893 return ConstantFoldLoadInst(LI, TD);
Frits van Bommela98214d2010-11-29 20:36:52 +0000894
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000895 if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +0000896 return ConstantExpr::getInsertValue(
897 cast<Constant>(IVI->getAggregateOperand()),
898 cast<Constant>(IVI->getInsertedValueOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +0000899 IVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000900 }
Frits van Bommela98214d2010-11-29 20:36:52 +0000901
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000902 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +0000903 return ConstantExpr::getExtractValue(
904 cast<Constant>(EVI->getAggregateOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +0000905 EVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000906 }
Frits van Bommela98214d2010-11-29 20:36:52 +0000907
Chad Rosierc24b86f2011-12-01 03:08:23 +0000908 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +0000909}
910
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000911static Constant *
912ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout *TD,
913 const TargetLibraryInfo *TLI,
914 SmallPtrSet<ConstantExpr *, 4> &FoldedOps) {
915 SmallVector<Constant *, 8> Ops;
916 for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end(); i != e;
917 ++i) {
Dan Gohman580b80d2009-11-23 16:22:21 +0000918 Constant *NewC = cast<Constant>(*i);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000919 // Recursively fold the ConstantExpr's operands. If we have already folded
920 // a ConstantExpr, we don't have to process it again.
921 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC)) {
922 if (FoldedOps.insert(NewCE))
923 NewC = ConstantFoldConstantExpressionImpl(NewCE, TD, TLI, FoldedOps);
924 }
Dan Gohman580b80d2009-11-23 16:22:21 +0000925 Ops.push_back(NewC);
926 }
Nick Lewyckyf6ccd252008-05-25 20:56:15 +0000927
928 if (CE->isCompare())
Chris Lattnercdfb80d2009-11-09 23:06:58 +0000929 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
Chad Rosierc24b86f2011-12-01 03:08:23 +0000930 TD, TLI);
931 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +0000932}
933
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000934/// ConstantFoldConstantExpression - Attempt to fold the constant expression
935/// using the specified DataLayout. If successful, the constant result is
936/// result is returned, if not, null is returned.
937Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
938 const DataLayout *TD,
939 const TargetLibraryInfo *TLI) {
940 SmallPtrSet<ConstantExpr *, 4> FoldedOps;
941 return ConstantFoldConstantExpressionImpl(CE, TD, TLI, FoldedOps);
942}
943
Chris Lattner2ae054a2007-01-30 23:45:45 +0000944/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
945/// specified opcode and operands. If successful, the constant result is
946/// returned, if not, null is returned. Note that this function can fail when
947/// attempting to fold instructions like loads and stores, which have no
948/// constant expression form.
949///
Dan Gohman580b80d2009-11-23 16:22:21 +0000950/// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
951/// information, due to only being passed an opcode and operands. Constant
952/// folding using this function strips this information.
953///
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000954Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
Jay Foadf4b14a22011-07-19 13:32:40 +0000955 ArrayRef<Constant *> Ops,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000956 const DataLayout *TD,
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000957 const TargetLibraryInfo *TLI) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000958 // Handle easy binops first.
Chris Lattnerd2265b42007-12-10 22:53:04 +0000959 if (Instruction::isBinaryOp(Opcode)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000960 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1])) {
Chris Lattner46b5c642009-11-06 04:27:31 +0000961 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
Chris Lattner44d68b92007-01-31 00:51:48 +0000962 return C;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000963 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000964
Owen Anderson487375e2009-07-29 18:55:55 +0000965 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Chris Lattner44d68b92007-01-31 00:51:48 +0000966 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000967
Chris Lattnerd2265b42007-12-10 22:53:04 +0000968 switch (Opcode) {
Chris Lattner2ae054a2007-01-30 23:45:45 +0000969 default: return 0;
Chris Lattner8fb74c62010-01-02 01:22:23 +0000970 case Instruction::ICmp:
Craig Toppera2886c22012-02-07 05:05:23 +0000971 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
Chris Lattner2ae054a2007-01-30 23:45:45 +0000972 case Instruction::Call:
Jay Foadf4b14a22011-07-19 13:32:40 +0000973 if (Function *F = dyn_cast<Function>(Ops.back()))
Chris Lattner2ae054a2007-01-30 23:45:45 +0000974 if (canConstantFoldCallTo(F))
Chad Rosierc24b86f2011-12-01 03:08:23 +0000975 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +0000976 return 0;
Chris Lattner460e34a2007-08-11 23:49:01 +0000977 case Instruction::PtrToInt:
978 // If the input is a inttoptr, eliminate the pair. This requires knowing
979 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
980 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
981 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
982 Constant *Input = CE->getOperand(0);
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000983 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Matt Arsenaultd12e8022013-09-17 23:23:16 +0000984 unsigned PtrWidth = TD->getPointerTypeSizeInBits(CE->getType());
985 if (PtrWidth < InWidth) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000986 Constant *Mask =
Matt Arsenaultd12e8022013-09-17 23:23:16 +0000987 ConstantInt::get(CE->getContext(),
988 APInt::getLowBitsSet(InWidth, PtrWidth));
Owen Anderson487375e2009-07-29 18:55:55 +0000989 Input = ConstantExpr::getAnd(Input, Mask);
Nick Lewycky730d5da2008-10-24 06:14:27 +0000990 }
Chris Lattner460e34a2007-08-11 23:49:01 +0000991 // Do a zext or trunc to get to the dest size.
Owen Anderson487375e2009-07-29 18:55:55 +0000992 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner460e34a2007-08-11 23:49:01 +0000993 }
994 }
Owen Anderson487375e2009-07-29 18:55:55 +0000995 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner460e34a2007-08-11 23:49:01 +0000996 case Instruction::IntToPtr:
Duncan Sandsea68a6c2008-08-13 20:20:35 +0000997 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000998 // the int size is >= the ptr size and the address spaces are the same.
999 // This requires knowing the width of a pointer, so it can't be done in
1000 // ConstantExpr::getCast.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001001 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
1002 if (TD && CE->getOpcode() == Instruction::PtrToInt) {
1003 Constant *SrcPtr = CE->getOperand(0);
1004 unsigned SrcPtrSize = TD->getPointerTypeSizeInBits(SrcPtr->getType());
1005 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1006
1007 if (MidIntSize >= SrcPtrSize) {
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001008 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1009 if (SrcAS == DestTy->getPointerAddressSpace())
Matt Arsenault7a960a82013-08-20 21:20:04 +00001010 return FoldBitCast(CE->getOperand(0), DestTy, *TD);
1011 }
1012 }
1013 }
Dan Gohman8a0eb362010-02-23 16:35:41 +00001014
Owen Anderson487375e2009-07-29 18:55:55 +00001015 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001016 case Instruction::Trunc:
1017 case Instruction::ZExt:
1018 case Instruction::SExt:
1019 case Instruction::FPTrunc:
1020 case Instruction::FPExt:
1021 case Instruction::UIToFP:
1022 case Instruction::SIToFP:
1023 case Instruction::FPToUI:
1024 case Instruction::FPToSI:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001025 case Instruction::AddrSpaceCast:
Owen Anderson487375e2009-07-29 18:55:55 +00001026 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001027 case Instruction::BitCast:
Chris Lattner6a6b3fb2007-12-11 07:29:44 +00001028 if (TD)
Chris Lattner9d051242009-10-25 06:08:26 +00001029 return FoldBitCast(Ops[0], DestTy, *TD);
Owen Anderson487375e2009-07-29 18:55:55 +00001030 return ConstantExpr::getBitCast(Ops[0], DestTy);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001031 case Instruction::Select:
Owen Anderson487375e2009-07-29 18:55:55 +00001032 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001033 case Instruction::ExtractElement:
Owen Anderson487375e2009-07-29 18:55:55 +00001034 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001035 case Instruction::InsertElement:
Owen Anderson487375e2009-07-29 18:55:55 +00001036 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001037 case Instruction::ShuffleVector:
Owen Anderson487375e2009-07-29 18:55:55 +00001038 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001039 case Instruction::GetElementPtr:
Chad Rosierc24b86f2011-12-01 03:08:23 +00001040 if (Constant *C = CastGEPIndices(Ops, DestTy, TD, TLI))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00001041 return C;
Chad Rosierc24b86f2011-12-01 03:08:23 +00001042 if (Constant *C = SymbolicallyEvaluateGEP(Ops, DestTy, TD, TLI))
Chris Lattner44d68b92007-01-31 00:51:48 +00001043 return C;
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001044
Jay Foaded8db7d2011-07-21 14:31:17 +00001045 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
Chris Lattner2ae054a2007-01-30 23:45:45 +00001046 }
1047}
1048
Chris Lattnerd2265b42007-12-10 22:53:04 +00001049/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
1050/// instruction (icmp/fcmp) with the specified operands. If it fails, it
1051/// returns a constant expression of the specified operands.
1052///
1053Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001054 Constant *Ops0, Constant *Ops1,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001055 const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001056 const TargetLibraryInfo *TLI) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001057 // fold: icmp (inttoptr x), null -> icmp x, 0
1058 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001059 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd2265b42007-12-10 22:53:04 +00001060 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1061 //
1062 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
1063 // around to know if bit truncation is happening.
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001064 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1065 if (TD && Ops1->isNullValue()) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001066 if (CE0->getOpcode() == Instruction::IntToPtr) {
Matt Arsenault7a960a82013-08-20 21:20:04 +00001067 Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
Chris Lattnerd2265b42007-12-10 22:53:04 +00001068 // Convert the integer value to the right size to ensure we get the
1069 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001070 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd2265b42007-12-10 22:53:04 +00001071 IntPtrTy, false);
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001072 Constant *Null = Constant::getNullValue(C->getType());
Chad Rosierc24b86f2011-12-01 03:08:23 +00001073 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001074 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001075
Chris Lattnerd2265b42007-12-10 22:53:04 +00001076 // Only do this transformation if the int is intptrty in size, otherwise
1077 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001078 if (CE0->getOpcode() == Instruction::PtrToInt) {
1079 Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
1080 if (CE0->getType() == IntPtrTy) {
1081 Constant *C = CE0->getOperand(0);
1082 Constant *Null = Constant::getNullValue(C->getType());
1083 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
1084 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001085 }
1086 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001087
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001088 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001089 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001090 if (CE0->getOpcode() == Instruction::IntToPtr) {
Matt Arsenault7a960a82013-08-20 21:20:04 +00001091 Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
1092
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001093 // Convert the integer value to the right size to ensure we get the
1094 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001095 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001096 IntPtrTy, false);
Owen Anderson487375e2009-07-29 18:55:55 +00001097 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001098 IntPtrTy, false);
Chad Rosierc24b86f2011-12-01 03:08:23 +00001099 return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001100 }
1101
Chandler Carruth7ec50852012-11-01 08:07:29 +00001102 // Only do this transformation if the int is intptrty in size, otherwise
1103 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001104 if (CE0->getOpcode() == Instruction::PtrToInt) {
1105 Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
1106 if (CE0->getType() == IntPtrTy &&
1107 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1108 return ConstantFoldCompareInstOperands(Predicate,
1109 CE0->getOperand(0),
1110 CE1->getOperand(0),
1111 TD,
1112 TLI);
1113 }
1114 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001115 }
1116 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001117
Chris Lattner8fb74c62010-01-02 01:22:23 +00001118 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1119 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1120 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1121 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001122 Constant *LHS =
Chad Rosierc24b86f2011-12-01 03:08:23 +00001123 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,
1124 TD, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001125 Constant *RHS =
Chad Rosierc24b86f2011-12-01 03:08:23 +00001126 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,
1127 TD, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001128 unsigned OpC =
Chris Lattner8fb74c62010-01-02 01:22:23 +00001129 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1130 Constant *Ops[] = { LHS, RHS };
Chad Rosierc24b86f2011-12-01 03:08:23 +00001131 return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD, TLI);
Chris Lattner8fb74c62010-01-02 01:22:23 +00001132 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001133 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001134
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001135 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001136}
1137
1138
Chris Lattner2ae054a2007-01-30 23:45:45 +00001139/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
1140/// getelementptr constantexpr, return the constant value being addressed by the
1141/// constant expression, or null if something is funny and we can't decide.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001142Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmane525d9d2009-10-05 16:36:26 +00001143 ConstantExpr *CE) {
Chris Lattnerf488b352012-01-24 05:43:50 +00001144 if (!CE->getOperand(1)->isNullValue())
Chris Lattner2ae054a2007-01-30 23:45:45 +00001145 return 0; // Do not allow stepping over the value!
Chris Lattner67058832012-01-25 06:48:06 +00001146
1147 // Loop over all of the operands, tracking down which value we are
1148 // addressing.
1149 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1150 C = C->getAggregateElement(CE->getOperand(i));
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001151 if (C == 0)
1152 return 0;
Chris Lattner67058832012-01-25 06:48:06 +00001153 }
1154 return C;
Chris Lattnerf488b352012-01-24 05:43:50 +00001155}
1156
1157/// ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr
1158/// indices (with an *implied* zero pointer index that is not in the list),
1159/// return the constant value being addressed by a virtual load, or null if
1160/// something is funny and we can't decide.
1161Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1162 ArrayRef<Constant*> Indices) {
Chris Lattner2ae054a2007-01-30 23:45:45 +00001163 // Loop over all of the operands, tracking down which value we are
Chris Lattnerf488b352012-01-24 05:43:50 +00001164 // addressing.
1165 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +00001166 C = C->getAggregateElement(Indices[i]);
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001167 if (C == 0)
1168 return 0;
Chris Lattnerf488b352012-01-24 05:43:50 +00001169 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001170 return C;
1171}
1172
1173
1174//===----------------------------------------------------------------------===//
1175// Constant Folding for Calls
1176//
John Criswell970af112005-10-27 16:00:10 +00001177
1178/// canConstantFoldCallTo - Return true if its even possible to fold a call to
1179/// the specified function.
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001180bool llvm::canConstantFoldCallTo(const Function *F) {
John Criswell970af112005-10-27 16:00:10 +00001181 switch (F->getIntrinsicID()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001182 case Intrinsic::fabs:
1183 case Intrinsic::log:
1184 case Intrinsic::log2:
1185 case Intrinsic::log10:
1186 case Intrinsic::exp:
1187 case Intrinsic::exp2:
1188 case Intrinsic::floor:
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001189 case Intrinsic::ceil:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001190 case Intrinsic::sqrt:
Chad Rosier0155a632011-12-03 00:00:03 +00001191 case Intrinsic::pow:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001192 case Intrinsic::powi:
Reid Spencer6bba6c82007-04-01 07:35:23 +00001193 case Intrinsic::bswap:
1194 case Intrinsic::ctpop:
1195 case Intrinsic::ctlz:
1196 case Intrinsic::cttz:
Matt Arsenault83778582014-03-05 00:02:00 +00001197 case Intrinsic::fma:
1198 case Intrinsic::fmuladd:
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001199 case Intrinsic::copysign:
Karthik Bhatb67688a2014-03-07 04:36:21 +00001200 case Intrinsic::round:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001201 case Intrinsic::sadd_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001202 case Intrinsic::uadd_with_overflow:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001203 case Intrinsic::ssub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001204 case Intrinsic::usub_with_overflow:
Chris Lattner698661c2010-10-14 00:05:07 +00001205 case Intrinsic::smul_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001206 case Intrinsic::umul_with_overflow:
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001207 case Intrinsic::convert_from_fp16:
1208 case Intrinsic::convert_to_fp16:
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001209 case Intrinsic::x86_sse_cvtss2si:
1210 case Intrinsic::x86_sse_cvtss2si64:
1211 case Intrinsic::x86_sse_cvttss2si:
1212 case Intrinsic::x86_sse_cvttss2si64:
1213 case Intrinsic::x86_sse2_cvtsd2si:
1214 case Intrinsic::x86_sse2_cvtsd2si64:
1215 case Intrinsic::x86_sse2_cvttsd2si:
1216 case Intrinsic::x86_sse2_cvttsd2si64:
John Criswell970af112005-10-27 16:00:10 +00001217 return true;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001218 default:
1219 return false;
1220 case 0: break;
John Criswell970af112005-10-27 16:00:10 +00001221 }
1222
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001223 if (!F->hasName())
1224 return false;
Daniel Dunbarca414c72009-07-26 08:34:35 +00001225 StringRef Name = F->getName();
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001226
Chris Lattner785f9982007-08-08 06:55:43 +00001227 // In these cases, the check of the length is required. We don't want to
1228 // return true for a name like "cos\0blah" which strcmp would return equal to
1229 // "cos", but has length 8.
Daniel Dunbarca414c72009-07-26 08:34:35 +00001230 switch (Name[0]) {
Chris Lattner785f9982007-08-08 06:55:43 +00001231 default: return false;
1232 case 'a':
Chad Rosierc0955a52013-02-20 23:57:30 +00001233 return Name == "acos" || Name == "asin" || Name == "atan" || Name =="atan2";
Chris Lattner785f9982007-08-08 06:55:43 +00001234 case 'c':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001235 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
Chris Lattner785f9982007-08-08 06:55:43 +00001236 case 'e':
Chris Lattner713d5232011-05-22 22:22:35 +00001237 return Name == "exp" || Name == "exp2";
Chris Lattner785f9982007-08-08 06:55:43 +00001238 case 'f':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001239 return Name == "fabs" || Name == "fmod" || Name == "floor";
Chris Lattner785f9982007-08-08 06:55:43 +00001240 case 'l':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001241 return Name == "log" || Name == "log10";
Chris Lattner785f9982007-08-08 06:55:43 +00001242 case 'p':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001243 return Name == "pow";
Chris Lattner785f9982007-08-08 06:55:43 +00001244 case 's':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001245 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1246 Name == "sinf" || Name == "sqrtf";
Chris Lattner785f9982007-08-08 06:55:43 +00001247 case 't':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001248 return Name == "tan" || Name == "tanh";
John Criswell970af112005-10-27 16:00:10 +00001249 }
1250}
1251
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001252static Constant *GetConstantFoldFPValue(double V, Type *Ty) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001253 if (Ty->isHalfTy()) {
1254 APFloat APF(V);
1255 bool unused;
1256 APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1257 return ConstantFP::get(Ty->getContext(), APF);
1258 }
Chris Lattner351534f2009-10-05 05:06:24 +00001259 if (Ty->isFloatTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001260 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
Chris Lattner351534f2009-10-05 05:06:24 +00001261 if (Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001262 return ConstantFP::get(Ty->getContext(), APFloat(V));
Owen Andersond4ebfd82013-02-06 22:43:31 +00001263 llvm_unreachable("Can only constant fold half/float/double");
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001264
1265}
1266
1267static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
1268 Type *Ty) {
1269 sys::llvm_fenv_clearexcept();
1270 V = NativeFP(V);
1271 if (sys::llvm_fenv_testexcept()) {
1272 sys::llvm_fenv_clearexcept();
1273 return 0;
1274 }
1275
1276 return GetConstantFoldFPValue(V, Ty);
John Criswell970af112005-10-27 16:00:10 +00001277}
1278
Dan Gohman72efc042007-07-16 15:26:22 +00001279static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
Chris Lattner229907c2011-07-18 04:54:35 +00001280 double V, double W, Type *Ty) {
Dan Gohmanb48f9042010-09-17 20:06:27 +00001281 sys::llvm_fenv_clearexcept();
Dan Gohman72efc042007-07-16 15:26:22 +00001282 V = NativeFP(V, W);
Dan Gohmanb48f9042010-09-17 20:06:27 +00001283 if (sys::llvm_fenv_testexcept()) {
1284 sys::llvm_fenv_clearexcept();
Chris Lattner519a51a2008-03-30 18:02:00 +00001285 return 0;
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001286 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001287
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001288 return GetConstantFoldFPValue(V, Ty);
Dan Gohman72efc042007-07-16 15:26:22 +00001289}
1290
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001291/// ConstantFoldConvertToInt - Attempt to an SSE floating point to integer
1292/// conversion of a constant floating point. If roundTowardZero is false, the
1293/// default IEEE rounding is used (toward nearest, ties to even). This matches
1294/// the behavior of the non-truncating SSE instructions in the default rounding
1295/// mode. The desired integer type Ty is used to select how many bits are
1296/// available for the result. Returns null if the conversion cannot be
1297/// performed, otherwise returns the Constant value resulting from the
1298/// conversion.
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001299static Constant *ConstantFoldConvertToInt(const APFloat &Val,
1300 bool roundTowardZero, Type *Ty) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001301 // All of these conversion intrinsics form an integer of at most 64bits.
Matt Arsenault8c789092013-08-12 23:15:58 +00001302 unsigned ResultWidth = Ty->getIntegerBitWidth();
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001303 assert(ResultWidth <= 64 &&
1304 "Can only constant fold conversions to 64 and 32 bit ints");
1305
1306 uint64_t UIntVal;
1307 bool isExact = false;
1308 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1309 : APFloat::rmNearestTiesToEven;
1310 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1311 /*isSigned=*/true, mode,
1312 &isExact);
1313 if (status != APFloat::opOK && status != APFloat::opInexact)
1314 return 0;
1315 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1316}
1317
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001318static double getValueAsDouble(ConstantFP *Op) {
1319 Type *Ty = Op->getType();
1320
1321 if (Ty->isFloatTy())
1322 return Op->getValueAPF().convertToFloat();
1323
1324 if (Ty->isDoubleTy())
1325 return Op->getValueAPF().convertToDouble();
1326
1327 bool unused;
1328 APFloat APF = Op->getValueAPF();
1329 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1330 return APF.convertToDouble();
1331}
1332
Benjamin Kramer061d1472014-03-05 19:41:48 +00001333static Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID,
1334 Type *Ty, ArrayRef<Constant *> Operands,
1335 const TargetLibraryInfo *TLI) {
Jay Foadf4b14a22011-07-19 13:32:40 +00001336 if (Operands.size() == 1) {
John Criswell970af112005-10-27 16:00:10 +00001337 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001338 if (IntrinsicID == Intrinsic::convert_to_fp16) {
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001339 APFloat Val(Op->getValueAPF());
1340
1341 bool lost = false;
1342 Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1343
Benjamin Kramer061d1472014-03-05 19:41:48 +00001344 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001345 }
1346
Owen Andersond4ebfd82013-02-06 22:43:31 +00001347 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001348 return 0;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001349
Karthik Bhatb67688a2014-03-07 04:36:21 +00001350 if (IntrinsicID == Intrinsic::round) {
1351 APFloat V = Op->getValueAPF();
1352 V.roundToIntegral(APFloat::rmNearestTiesToAway);
1353 return ConstantFP::get(Ty->getContext(), V);
1354 }
1355
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001356 /// We only fold functions with finite arguments. Folding NaN and inf is
1357 /// likely to be aborted with an exception anyway, and some host libms
1358 /// have known errors raising exceptions.
1359 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1360 return 0;
1361
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001362 /// Currently APFloat versions of these functions do not exist, so we use
1363 /// the host native double versions. Float versions are not called
1364 /// directly but for all these it is true (float)(f((double)arg)) ==
1365 /// f(arg). Long double not supported yet.
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001366 double V = getValueAsDouble(Op);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001367
Benjamin Kramer061d1472014-03-05 19:41:48 +00001368 switch (IntrinsicID) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001369 default: break;
1370 case Intrinsic::fabs:
1371 return ConstantFoldFP(fabs, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001372#if HAVE_LOG2
Owen Andersond4ebfd82013-02-06 22:43:31 +00001373 case Intrinsic::log2:
1374 return ConstantFoldFP(log2, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001375#endif
1376#if HAVE_LOG
Owen Andersond4ebfd82013-02-06 22:43:31 +00001377 case Intrinsic::log:
1378 return ConstantFoldFP(log, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001379#endif
1380#if HAVE_LOG10
Owen Andersond4ebfd82013-02-06 22:43:31 +00001381 case Intrinsic::log10:
1382 return ConstantFoldFP(log10, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001383#endif
1384#if HAVE_EXP
Owen Andersond4ebfd82013-02-06 22:43:31 +00001385 case Intrinsic::exp:
1386 return ConstantFoldFP(exp, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001387#endif
1388#if HAVE_EXP2
Owen Andersond4ebfd82013-02-06 22:43:31 +00001389 case Intrinsic::exp2:
1390 return ConstantFoldFP(exp2, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001391#endif
Owen Andersond4ebfd82013-02-06 22:43:31 +00001392 case Intrinsic::floor:
1393 return ConstantFoldFP(floor, V, Ty);
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001394 case Intrinsic::ceil:
1395 return ConstantFoldFP(ceil, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001396 }
1397
Benjamin Kramer061d1472014-03-05 19:41:48 +00001398 if (!TLI)
1399 return 0;
1400
Daniel Dunbarca414c72009-07-26 08:34:35 +00001401 switch (Name[0]) {
Chris Lattner785f9982007-08-08 06:55:43 +00001402 case 'a':
Chad Rosier576c0f82011-12-01 23:16:03 +00001403 if (Name == "acos" && TLI->has(LibFunc::acos))
Chris Lattner46b5c642009-11-06 04:27:31 +00001404 return ConstantFoldFP(acos, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001405 else if (Name == "asin" && TLI->has(LibFunc::asin))
Chris Lattner46b5c642009-11-06 04:27:31 +00001406 return ConstantFoldFP(asin, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001407 else if (Name == "atan" && TLI->has(LibFunc::atan))
Chris Lattner46b5c642009-11-06 04:27:31 +00001408 return ConstantFoldFP(atan, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001409 break;
1410 case 'c':
Chad Rosier576c0f82011-12-01 23:16:03 +00001411 if (Name == "ceil" && TLI->has(LibFunc::ceil))
Chris Lattner46b5c642009-11-06 04:27:31 +00001412 return ConstantFoldFP(ceil, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001413 else if (Name == "cos" && TLI->has(LibFunc::cos))
Chris Lattner46b5c642009-11-06 04:27:31 +00001414 return ConstantFoldFP(cos, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001415 else if (Name == "cosh" && TLI->has(LibFunc::cosh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001416 return ConstantFoldFP(cosh, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001417 else if (Name == "cosf" && TLI->has(LibFunc::cosf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001418 return ConstantFoldFP(cos, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001419 break;
1420 case 'e':
Chad Rosier576c0f82011-12-01 23:16:03 +00001421 if (Name == "exp" && TLI->has(LibFunc::exp))
Chris Lattner46b5c642009-11-06 04:27:31 +00001422 return ConstantFoldFP(exp, V, Ty);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001423
Chad Rosier576c0f82011-12-01 23:16:03 +00001424 if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
Chris Lattner713d5232011-05-22 22:22:35 +00001425 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1426 // C99 library.
1427 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1428 }
Chris Lattner785f9982007-08-08 06:55:43 +00001429 break;
1430 case 'f':
Chad Rosier576c0f82011-12-01 23:16:03 +00001431 if (Name == "fabs" && TLI->has(LibFunc::fabs))
Chris Lattner46b5c642009-11-06 04:27:31 +00001432 return ConstantFoldFP(fabs, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001433 else if (Name == "floor" && TLI->has(LibFunc::floor))
Chris Lattner46b5c642009-11-06 04:27:31 +00001434 return ConstantFoldFP(floor, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001435 break;
1436 case 'l':
Chad Rosier576c0f82011-12-01 23:16:03 +00001437 if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
Chris Lattner46b5c642009-11-06 04:27:31 +00001438 return ConstantFoldFP(log, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001439 else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
Chris Lattner46b5c642009-11-06 04:27:31 +00001440 return ConstantFoldFP(log10, V, Ty);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001441 else if (IntrinsicID == Intrinsic::sqrt &&
Owen Andersond4ebfd82013-02-06 22:43:31 +00001442 (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
Chris Lattner785f9982007-08-08 06:55:43 +00001443 if (V >= -0.0)
Chris Lattner46b5c642009-11-06 04:27:31 +00001444 return ConstantFoldFP(sqrt, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001445 else // Undefined
Owen Anderson5a1acd92009-07-31 20:28:14 +00001446 return Constant::getNullValue(Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001447 }
1448 break;
1449 case 's':
Chad Rosier576c0f82011-12-01 23:16:03 +00001450 if (Name == "sin" && TLI->has(LibFunc::sin))
Chris Lattner46b5c642009-11-06 04:27:31 +00001451 return ConstantFoldFP(sin, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001452 else if (Name == "sinh" && TLI->has(LibFunc::sinh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001453 return ConstantFoldFP(sinh, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001454 else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
Chris Lattner46b5c642009-11-06 04:27:31 +00001455 return ConstantFoldFP(sqrt, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001456 else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001457 return ConstantFoldFP(sqrt, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001458 else if (Name == "sinf" && TLI->has(LibFunc::sinf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001459 return ConstantFoldFP(sin, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001460 break;
1461 case 't':
Chad Rosier576c0f82011-12-01 23:16:03 +00001462 if (Name == "tan" && TLI->has(LibFunc::tan))
Chris Lattner46b5c642009-11-06 04:27:31 +00001463 return ConstantFoldFP(tan, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001464 else if (Name == "tanh" && TLI->has(LibFunc::tanh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001465 return ConstantFoldFP(tanh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001466 break;
1467 default:
1468 break;
John Criswell970af112005-10-27 16:00:10 +00001469 }
Chris Lattner9ca7c092009-10-05 05:00:35 +00001470 return 0;
1471 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001472
Chris Lattner9ca7c092009-10-05 05:00:35 +00001473 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001474 switch (IntrinsicID) {
Chandler Carruth352d9b12011-01-10 09:02:58 +00001475 case Intrinsic::bswap:
Benjamin Kramer061d1472014-03-05 19:41:48 +00001476 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001477 case Intrinsic::ctpop:
Owen Andersonedb4a702009-07-24 23:12:02 +00001478 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001479 case Intrinsic::convert_from_fp16: {
Tim Northover29178a32013-01-22 09:46:31 +00001480 APFloat Val(APFloat::IEEEhalf, Op->getValue());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001481
1482 bool lost = false;
1483 APFloat::opStatus status =
1484 Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
1485
1486 // Conversion is always precise.
Jeffrey Yasskin9b43f332010-12-23 00:58:24 +00001487 (void)status;
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001488 assert(status == APFloat::opOK && !lost &&
1489 "Precision lost during fp16 constfolding");
1490
Benjamin Kramer061d1472014-03-05 19:41:48 +00001491 return ConstantFP::get(Ty->getContext(), Val);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001492 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001493 default:
1494 return 0;
1495 }
John Criswell970af112005-10-27 16:00:10 +00001496 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001497
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001498 // Support ConstantVector in case we have an Undef in the top.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001499 if (isa<ConstantVector>(Operands[0]) ||
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001500 isa<ConstantDataVector>(Operands[0])) {
1501 Constant *Op = cast<Constant>(Operands[0]);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001502 switch (IntrinsicID) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001503 default: break;
1504 case Intrinsic::x86_sse_cvtss2si:
1505 case Intrinsic::x86_sse_cvtss2si64:
1506 case Intrinsic::x86_sse2_cvtsd2si:
1507 case Intrinsic::x86_sse2_cvtsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001508 if (ConstantFP *FPOp =
1509 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1510 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1511 /*roundTowardZero=*/false, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001512 case Intrinsic::x86_sse_cvttss2si:
1513 case Intrinsic::x86_sse_cvttss2si64:
1514 case Intrinsic::x86_sse2_cvttsd2si:
1515 case Intrinsic::x86_sse2_cvttsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001516 if (ConstantFP *FPOp =
1517 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001518 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001519 /*roundTowardZero=*/true, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001520 }
1521 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001522
Dan Gohmancf39be32010-02-17 00:54:58 +00001523 if (isa<UndefValue>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001524 if (IntrinsicID == Intrinsic::bswap)
Dan Gohmancf39be32010-02-17 00:54:58 +00001525 return Operands[0];
1526 return 0;
1527 }
1528
Chris Lattner9ca7c092009-10-05 05:00:35 +00001529 return 0;
1530 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001531
Jay Foadf4b14a22011-07-19 13:32:40 +00001532 if (Operands.size() == 2) {
John Criswell970af112005-10-27 16:00:10 +00001533 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001534 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001535 return 0;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001536 double Op1V = getValueAsDouble(Op1);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001537
John Criswell970af112005-10-27 16:00:10 +00001538 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattner351534f2009-10-05 05:06:24 +00001539 if (Op2->getType() != Op1->getType())
1540 return 0;
Chad Rosier576c0f82011-12-01 23:16:03 +00001541
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001542 double Op2V = getValueAsDouble(Op2);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001543 if (IntrinsicID == Intrinsic::pow) {
Chad Rosier0155a632011-12-03 00:00:03 +00001544 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1545 }
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001546 if (IntrinsicID == Intrinsic::copysign) {
1547 APFloat V1 = Op1->getValueAPF();
1548 APFloat V2 = Op2->getValueAPF();
1549 V1.copySign(V2);
1550 return ConstantFP::get(Ty->getContext(), V1);
1551 }
Chad Rosier0155a632011-12-03 00:00:03 +00001552 if (!TLI)
1553 return 0;
Chad Rosier576c0f82011-12-01 23:16:03 +00001554 if (Name == "pow" && TLI->has(LibFunc::pow))
Chris Lattner46b5c642009-11-06 04:27:31 +00001555 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001556 if (Name == "fmod" && TLI->has(LibFunc::fmod))
Chris Lattner46b5c642009-11-06 04:27:31 +00001557 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001558 if (Name == "atan2" && TLI->has(LibFunc::atan2))
Chris Lattner46b5c642009-11-06 04:27:31 +00001559 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
Chris Lattner26933dd2007-01-15 06:27:37 +00001560 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001561 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1562 return ConstantFP::get(Ty->getContext(),
Owen Andersond4ebfd82013-02-06 22:43:31 +00001563 APFloat((float)std::pow((float)Op1V,
1564 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001565 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1566 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001567 APFloat((float)std::pow((float)Op1V,
Chris Lattner3b187622008-04-20 00:41:09 +00001568 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001569 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1570 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001571 APFloat((double)std::pow((double)Op1V,
1572 (int)Op2C->getZExtValue())));
John Criswell970af112005-10-27 16:00:10 +00001573 }
Chris Lattner9ca7c092009-10-05 05:00:35 +00001574 return 0;
John Criswell970af112005-10-27 16:00:10 +00001575 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001576
Chris Lattner59d93982009-10-05 05:26:04 +00001577 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1578 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001579 switch (IntrinsicID) {
Chris Lattner59d93982009-10-05 05:26:04 +00001580 default: break;
Chris Lattner698661c2010-10-14 00:05:07 +00001581 case Intrinsic::sadd_with_overflow:
1582 case Intrinsic::uadd_with_overflow:
1583 case Intrinsic::ssub_with_overflow:
1584 case Intrinsic::usub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001585 case Intrinsic::smul_with_overflow:
1586 case Intrinsic::umul_with_overflow: {
Chris Lattner698661c2010-10-14 00:05:07 +00001587 APInt Res;
1588 bool Overflow;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001589 switch (IntrinsicID) {
Craig Toppera2886c22012-02-07 05:05:23 +00001590 default: llvm_unreachable("Invalid case");
Chris Lattner698661c2010-10-14 00:05:07 +00001591 case Intrinsic::sadd_with_overflow:
1592 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1593 break;
1594 case Intrinsic::uadd_with_overflow:
1595 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1596 break;
1597 case Intrinsic::ssub_with_overflow:
1598 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1599 break;
1600 case Intrinsic::usub_with_overflow:
1601 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1602 break;
1603 case Intrinsic::smul_with_overflow:
1604 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1605 break;
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001606 case Intrinsic::umul_with_overflow:
1607 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1608 break;
Chris Lattner698661c2010-10-14 00:05:07 +00001609 }
Chris Lattner59d93982009-10-05 05:26:04 +00001610 Constant *Ops[] = {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001611 ConstantInt::get(Ty->getContext(), Res),
1612 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
Chris Lattner59d93982009-10-05 05:26:04 +00001613 };
Benjamin Kramer061d1472014-03-05 19:41:48 +00001614 return ConstantStruct::get(cast<StructType>(Ty), Ops);
Chris Lattner59d93982009-10-05 05:26:04 +00001615 }
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001616 case Intrinsic::cttz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001617 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1618 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001619 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1620 case Intrinsic::ctlz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001621 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1622 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001623 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
Chris Lattner59d93982009-10-05 05:26:04 +00001624 }
1625 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001626
Chris Lattner59d93982009-10-05 05:26:04 +00001627 return 0;
1628 }
1629 return 0;
John Criswell970af112005-10-27 16:00:10 +00001630 }
Matt Arsenault83778582014-03-05 00:02:00 +00001631
1632 if (Operands.size() != 3)
1633 return 0;
1634
1635 if (const ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1636 if (const ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1637 if (const ConstantFP *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001638 switch (IntrinsicID) {
Matt Arsenault83778582014-03-05 00:02:00 +00001639 default: break;
1640 case Intrinsic::fma:
1641 case Intrinsic::fmuladd: {
1642 APFloat V = Op1->getValueAPF();
1643 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1644 Op3->getValueAPF(),
1645 APFloat::rmNearestTiesToEven);
1646 if (s != APFloat::opInvalidOp)
1647 return ConstantFP::get(Ty->getContext(), V);
1648
1649 return 0;
1650 }
1651 }
1652 }
1653 }
1654 }
1655
John Criswell970af112005-10-27 16:00:10 +00001656 return 0;
1657}
Benjamin Kramer061d1472014-03-05 19:41:48 +00001658
1659static Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1660 VectorType *VTy,
1661 ArrayRef<Constant *> Operands,
1662 const TargetLibraryInfo *TLI) {
1663 SmallVector<Constant *, 4> Result(VTy->getNumElements());
1664 SmallVector<Constant *, 4> Lane(Operands.size());
1665 Type *Ty = VTy->getElementType();
1666
1667 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1668 // Gather a column of constants.
1669 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1670 Constant *Agg = Operands[J]->getAggregateElement(I);
1671 if (!Agg)
1672 return nullptr;
1673
1674 Lane[J] = Agg;
1675 }
1676
1677 // Use the regular scalar folding to simplify this column.
1678 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1679 if (!Folded)
1680 return nullptr;
1681 Result[I] = Folded;
1682 }
1683
1684 return ConstantVector::get(Result);
1685}
1686
1687/// ConstantFoldCall - Attempt to constant fold a call to the specified function
1688/// with the specified arguments, returning null if unsuccessful.
1689Constant *
1690llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1691 const TargetLibraryInfo *TLI) {
1692 if (!F->hasName())
1693 return 0;
1694 StringRef Name = F->getName();
1695
1696 Type *Ty = F->getReturnType();
1697
1698 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1699 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, TLI);
1700
1701 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
1702}