blob: a7fb10b2d2b726e35355f473ba5962c750f2d977 [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"
David Majnemere61e4bf2016-06-21 05:10:24 +000020#include "llvm/ADT/STLExtras.h"
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +000021#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringMap.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000024#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Analysis/ValueTracking.h"
Alp Tokerc817d6a2014-06-09 18:28:53 +000026#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000031#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/Operator.h"
Torok Edwin56d06592009-07-11 20:10:48 +000036#include "llvm/Support/ErrorHandling.h"
John Criswell970af112005-10-27 16:00:10 +000037#include "llvm/Support/MathExtras.h"
Eugene Zelenko35623fb2016-03-28 17:40:08 +000038#include <cassert>
John Criswell970af112005-10-27 16:00:10 +000039#include <cerrno>
Eugene Zelenko35623fb2016-03-28 17:40:08 +000040#include <cfenv>
Jeff Cohencc08c832006-12-02 02:22:01 +000041#include <cmath>
Eugene Zelenko35623fb2016-03-28 17:40:08 +000042#include <limits>
Alp Tokerc817d6a2014-06-09 18:28:53 +000043
John Criswell970af112005-10-27 16:00:10 +000044using namespace llvm;
45
Eugene Zelenko35623fb2016-03-28 17:40:08 +000046namespace {
47
Chris Lattner44d68b92007-01-31 00:51:48 +000048//===----------------------------------------------------------------------===//
49// Constant Folding internal helper functions
50//===----------------------------------------------------------------------===//
51
Sanjay Patel0d7dee62014-10-02 15:13:22 +000052/// Constant fold bitcast, symbolically evaluating it with DataLayout.
53/// This always returns a non-null constant, but it may be a
Chris Lattner9d051242009-10-25 06:08:26 +000054/// ConstantExpr if unfoldable.
Eugene Zelenko35623fb2016-03-28 17:40:08 +000055Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
Nadav Rotem365af6f2011-08-24 20:18:38 +000056 // Catch the obvious splat cases.
57 if (C->isNullValue() && !DestTy->isX86_MMXTy())
58 return Constant::getNullValue(DestTy);
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +000059 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
60 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
Nadav Rotem365af6f2011-08-24 20:18:38 +000061 return Constant::getAllOnesValue(DestTy);
62
Rafael Espindolabb893fe2012-01-27 23:33:07 +000063 // Handle a vector->integer cast.
David Majnemer90a97042016-07-13 04:22:12 +000064 if (auto *IT = dyn_cast<IntegerType>(DestTy)) {
65 auto *VTy = dyn_cast<VectorType>(C->getType());
Craig Topper9f008862014-04-15 04:59:12 +000066 if (!VTy)
Rafael Espindolabb893fe2012-01-27 23:33:07 +000067 return ConstantExpr::getBitCast(C, DestTy);
68
Michael Ilsemana7b93c12013-02-26 22:51:07 +000069 unsigned NumSrcElts = VTy->getNumElements();
70 Type *SrcEltTy = VTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +000071
Rafael Espindolabb893fe2012-01-27 23:33:07 +000072 // If the vector is a vector of floating point, convert it to vector of int
73 // to simplify things.
Chris Lattner8213c8a2012-02-06 21:56:39 +000074 if (SrcEltTy->isFloatingPointTy()) {
75 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Rafael Espindolabb893fe2012-01-27 23:33:07 +000076 Type *SrcIVTy =
77 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
Chandler Carruthef860a22013-01-02 09:10:48 +000078 // Ask IR to do the conversion now that #elts line up.
Rafael Espindolabb893fe2012-01-27 23:33:07 +000079 C = ConstantExpr::getBitCast(C, SrcIVTy);
80 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000081
Rafael Espindolabb893fe2012-01-27 23:33:07 +000082 // Now that we know that the input value is a vector of integers, just shift
83 // and insert them into our result.
Igor Breger73578492016-06-27 06:42:54 +000084 unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
Rafael Espindolabb893fe2012-01-27 23:33:07 +000085 APInt Result(IT->getBitWidth(), 0);
86 for (unsigned i = 0; i != NumSrcElts; ++i) {
David Majnemer3918cdd2016-05-04 06:13:33 +000087 Constant *Element;
Mehdi Aminia28d91d2015-03-10 02:37:25 +000088 if (DL.isLittleEndian())
David Majnemer3918cdd2016-05-04 06:13:33 +000089 Element = C->getAggregateElement(NumSrcElts-i-1);
Chris Lattner8213c8a2012-02-06 21:56:39 +000090 else
David Majnemer3918cdd2016-05-04 06:13:33 +000091 Element = C->getAggregateElement(i);
92
David Majnemere4218cf2016-07-29 04:06:09 +000093 if (Element && isa<UndefValue>(Element)) {
94 Result <<= BitShift;
95 continue;
96 }
97
David Majnemer3918cdd2016-05-04 06:13:33 +000098 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
99 if (!ElementCI)
100 return ConstantExpr::getBitCast(C, DestTy);
101
102 Result <<= BitShift;
103 Result |= ElementCI->getValue().zextOrSelf(IT->getBitWidth());
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000104 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000105
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000106 return ConstantInt::get(IT, Result);
107 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000108
Nadav Rotemad4a70a2011-08-20 14:02:29 +0000109 // The code below only handles casts to vectors currently.
David Majnemer90a97042016-07-13 04:22:12 +0000110 auto *DestVTy = dyn_cast<VectorType>(DestTy);
Craig Topper9f008862014-04-15 04:59:12 +0000111 if (!DestVTy)
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000112 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000113
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000114 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
115 // vector so the code below can handle it uniformly.
116 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
117 Constant *Ops = C; // don't take the address of C!
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000118 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000119 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000120
Chris Lattner9d051242009-10-25 06:08:26 +0000121 // If this is a bitcast from constant vector -> vector, fold it.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000122 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000123 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000124
Chandler Carruthef860a22013-01-02 09:10:48 +0000125 // If the element types match, IR can fold it.
Chris Lattner9d051242009-10-25 06:08:26 +0000126 unsigned NumDstElt = DestVTy->getNumElements();
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000127 unsigned NumSrcElt = C->getType()->getVectorNumElements();
Chris Lattner9d051242009-10-25 06:08:26 +0000128 if (NumDstElt == NumSrcElt)
129 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000130
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000131 Type *SrcEltTy = C->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000132 Type *DstEltTy = DestVTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000133
134 // Otherwise, we're changing the number of elements in a vector, which
Chris Lattner9d051242009-10-25 06:08:26 +0000135 // requires endianness information to do the right thing. For example,
136 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
137 // folds to (little endian):
138 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
139 // and to (big endian):
140 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000141
Chris Lattner9d051242009-10-25 06:08:26 +0000142 // First thing is first. We only want to think about integer here, so if
143 // we have something in FP form, recast it as integer.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000144 if (DstEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000145 // Fold to an vector of integers with same size as our FP type.
146 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000147 Type *DestIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000148 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
149 // Recursively handle this integer conversion, if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000150 C = FoldBitCast(C, DestIVTy, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000151
Chandler Carruthef860a22013-01-02 09:10:48 +0000152 // Finally, IR can handle this now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000153 return ConstantExpr::getBitCast(C, DestTy);
154 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000155
Chris Lattner9d051242009-10-25 06:08:26 +0000156 // Okay, we know the destination is integer, if the input is FP, convert
157 // it to integer first.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000158 if (SrcEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000159 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000160 Type *SrcIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000161 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
Chandler Carruthef860a22013-01-02 09:10:48 +0000162 // Ask IR to do the conversion now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000163 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chandler Carruthef860a22013-01-02 09:10:48 +0000164 // If IR wasn't able to fold it, bail out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000165 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
166 !isa<ConstantDataVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000167 return C;
168 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000169
Chris Lattner9d051242009-10-25 06:08:26 +0000170 // Now we know that the input and output vectors are both integer vectors
171 // of the same size, and that their #elements is not the same. Do the
172 // conversion here, which depends on whether the input or output has
173 // more elements.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000174 bool isLittleEndian = DL.isLittleEndian();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000175
Chris Lattner9d051242009-10-25 06:08:26 +0000176 SmallVector<Constant*, 32> Result;
177 if (NumDstElt < NumSrcElt) {
178 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
179 Constant *Zero = Constant::getNullValue(DstEltTy);
180 unsigned Ratio = NumSrcElt/NumDstElt;
181 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
182 unsigned SrcElt = 0;
183 for (unsigned i = 0; i != NumDstElt; ++i) {
184 // Build each element of the result.
185 Constant *Elt = Zero;
186 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
187 for (unsigned j = 0; j != Ratio; ++j) {
David Majnemere4218cf2016-07-29 04:06:09 +0000188 Constant *Src = C->getAggregateElement(SrcElt++);
189 if (Src && isa<UndefValue>(Src))
David Majnemer718da3d2016-07-29 18:48:27 +0000190 Src = Constant::getNullValue(C->getType()->getVectorElementType());
David Majnemere4218cf2016-07-29 04:06:09 +0000191 else
192 Src = dyn_cast_or_null<ConstantInt>(Src);
Chris Lattner9d051242009-10-25 06:08:26 +0000193 if (!Src) // Reject constantexpr elements.
194 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000195
Chris Lattner9d051242009-10-25 06:08:26 +0000196 // Zero extend the element to the right size.
197 Src = ConstantExpr::getZExt(Src, Elt->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000198
Chris Lattner9d051242009-10-25 06:08:26 +0000199 // Shift it to the right place, depending on endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000200 Src = ConstantExpr::getShl(Src,
Chris Lattner9d051242009-10-25 06:08:26 +0000201 ConstantInt::get(Src->getType(), ShiftAmt));
202 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000203
Chris Lattner9d051242009-10-25 06:08:26 +0000204 // Mix it in.
205 Elt = ConstantExpr::getOr(Elt, Src);
206 }
207 Result.push_back(Elt);
208 }
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000209 return ConstantVector::get(Result);
210 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000211
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000212 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
213 unsigned Ratio = NumDstElt/NumSrcElt;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000214 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000215
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000216 // Loop over each source value, expanding into multiple results.
217 for (unsigned i = 0; i != NumSrcElt; ++i) {
David Majnemere4218cf2016-07-29 04:06:09 +0000218 auto *Src = dyn_cast_or_null<ConstantInt>(C->getAggregateElement(i));
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000219 if (!Src) // Reject constantexpr elements.
220 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000221
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000222 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
223 for (unsigned j = 0; j != Ratio; ++j) {
224 // Shift the piece of the value into the right place, depending on
225 // endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000226 Constant *Elt = ConstantExpr::getLShr(Src,
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000227 ConstantInt::get(Src->getType(), ShiftAmt));
228 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000229
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +0000230 // Truncate the element to an integer with the same pointer size and
231 // convert the element back to a pointer using a inttoptr.
232 if (DstEltTy->isPointerTy()) {
233 IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
234 Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
235 Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
236 continue;
237 }
238
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000239 // Truncate and remember this piece.
240 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner9d051242009-10-25 06:08:26 +0000241 }
242 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000243
Chris Lattner69229312011-02-15 00:14:00 +0000244 return ConstantVector::get(Result);
Chris Lattner9d051242009-10-25 06:08:26 +0000245}
246
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000247} // end anonymous namespace
248
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000249/// If this constant is a constant offset from a global, return the global and
250/// the constant. Because of constantexprs, this function is recursive.
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000251bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
252 APInt &Offset, const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000253 // Trivial case, constant is the global.
254 if ((GV = dyn_cast<GlobalValue>(C))) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000255 unsigned BitWidth = DL.getPointerTypeSizeInBits(GV->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000256 Offset = APInt(BitWidth, 0);
Chris Lattner44d68b92007-01-31 00:51:48 +0000257 return true;
258 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000259
Chris Lattner44d68b92007-01-31 00:51:48 +0000260 // Otherwise, if this isn't a constant expr, bail out.
David Majnemer90a97042016-07-13 04:22:12 +0000261 auto *CE = dyn_cast<ConstantExpr>(C);
Chris Lattner44d68b92007-01-31 00:51:48 +0000262 if (!CE) return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000263
Chris Lattner44d68b92007-01-31 00:51:48 +0000264 // Look through ptr->int and ptr->ptr casts.
265 if (CE->getOpcode() == Instruction::PtrToInt ||
Matt Arsenault95365ca2015-07-27 18:31:03 +0000266 CE->getOpcode() == Instruction::BitCast)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000267 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000268
269 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
David Majnemer90a97042016-07-13 04:22:12 +0000270 auto *GEP = dyn_cast<GEPOperator>(CE);
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000271 if (!GEP)
272 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000273
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000274 unsigned BitWidth = DL.getPointerTypeSizeInBits(GEP->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000275 APInt TmpOffset(BitWidth, 0);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000276
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000277 // If the base isn't a global+constant, we aren't either.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000278 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000279 return false;
280
281 // Otherwise, add any offset that our operands provide.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000282 if (!GEP->accumulateConstantOffset(DL, TmpOffset))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000283 return false;
284
285 Offset = TmpOffset;
286 return true;
Chris Lattner44d68b92007-01-31 00:51:48 +0000287}
288
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000289namespace {
290
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000291/// Recursive helper to read bits out of global. C is the constant being copied
292/// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
293/// results into and BytesLeft is the number of bytes left in
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000294/// the CurPtr buffer. DL is the DataLayout.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000295bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
296 unsigned BytesLeft, const DataLayout &DL) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000297 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
Chris Lattnered00b802009-10-23 06:23:49 +0000298 "Out of range access");
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000299
Chris Lattner3db7bd22009-10-24 05:27:19 +0000300 // If this element is zero or undefined, we can just return since *CurPtr is
301 // zero initialized.
Chris Lattnered00b802009-10-23 06:23:49 +0000302 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
303 return true;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000304
David Majnemer90a97042016-07-13 04:22:12 +0000305 if (auto *CI = dyn_cast<ConstantInt>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000306 if (CI->getBitWidth() > 64 ||
307 (CI->getBitWidth() & 7) != 0)
308 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000309
Chris Lattnered00b802009-10-23 06:23:49 +0000310 uint64_t Val = CI->getZExtValue();
311 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000312
Chris Lattnered00b802009-10-23 06:23:49 +0000313 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000314 int n = ByteOffset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000315 if (!DL.isLittleEndian())
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000316 n = IntBytes - n - 1;
317 CurPtr[i] = (unsigned char)(Val >> (n * 8));
Chris Lattnered00b802009-10-23 06:23:49 +0000318 ++ByteOffset;
319 }
320 return true;
321 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000322
David Majnemer90a97042016-07-13 04:22:12 +0000323 if (auto *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000324 if (CFP->getType()->isDoubleTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000325 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
326 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000327 }
328 if (CFP->getType()->isFloatTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000329 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
330 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000331 }
Owen Andersond4ebfd82013-02-06 22:43:31 +0000332 if (CFP->getType()->isHalfTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000333 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
334 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Owen Andersond4ebfd82013-02-06 22:43:31 +0000335 }
Chris Lattner3db7bd22009-10-24 05:27:19 +0000336 return false;
Chris Lattnered00b802009-10-23 06:23:49 +0000337 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000338
David Majnemer90a97042016-07-13 04:22:12 +0000339 if (auto *CS = dyn_cast<ConstantStruct>(C)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000340 const StructLayout *SL = DL.getStructLayout(CS->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000341 unsigned Index = SL->getElementContainingOffset(ByteOffset);
342 uint64_t CurEltOffset = SL->getElementOffset(Index);
343 ByteOffset -= CurEltOffset;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000344
Chris Lattnered00b802009-10-23 06:23:49 +0000345 while (1) {
346 // If the element access is to the element itself and not to tail padding,
347 // read the bytes from the element.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000348 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000349
350 if (ByteOffset < EltSize &&
351 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000352 BytesLeft, DL))
Chris Lattnered00b802009-10-23 06:23:49 +0000353 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000354
Chris Lattnered00b802009-10-23 06:23:49 +0000355 ++Index;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000356
Chris Lattnered00b802009-10-23 06:23:49 +0000357 // Check to see if we read from the last struct element, if so we're done.
358 if (Index == CS->getType()->getNumElements())
359 return true;
360
361 // If we read all of the bytes we needed from this element we're done.
362 uint64_t NextEltOffset = SL->getElementOffset(Index);
363
Matt Arsenault8c789092013-08-12 23:15:58 +0000364 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
Chris Lattnered00b802009-10-23 06:23:49 +0000365 return true;
366
367 // Move to the next element of the struct.
Matt Arsenault8c789092013-08-12 23:15:58 +0000368 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
369 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
Chris Lattnered00b802009-10-23 06:23:49 +0000370 ByteOffset = 0;
371 CurEltOffset = NextEltOffset;
372 }
373 // not reached.
374 }
375
Chris Lattner67058832012-01-25 06:48:06 +0000376 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
377 isa<ConstantDataSequential>(C)) {
Matt Arsenault8c789092013-08-12 23:15:58 +0000378 Type *EltTy = C->getType()->getSequentialElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000379 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
Chris Lattnered00b802009-10-23 06:23:49 +0000380 uint64_t Index = ByteOffset / EltSize;
381 uint64_t Offset = ByteOffset - Index * EltSize;
Chris Lattner67058832012-01-25 06:48:06 +0000382 uint64_t NumElts;
David Majnemer90a97042016-07-13 04:22:12 +0000383 if (auto *AT = dyn_cast<ArrayType>(C->getType()))
Chris Lattner67058832012-01-25 06:48:06 +0000384 NumElts = AT->getNumElements();
385 else
Matt Arsenault8c789092013-08-12 23:15:58 +0000386 NumElts = C->getType()->getVectorNumElements();
Duncan Sands0b875a02012-07-25 09:14:54 +0000387
Chris Lattner67058832012-01-25 06:48:06 +0000388 for (; Index != NumElts; ++Index) {
389 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000390 BytesLeft, DL))
Chris Lattner67058832012-01-25 06:48:06 +0000391 return false;
Duncan Sands0b875a02012-07-25 09:14:54 +0000392
393 uint64_t BytesWritten = EltSize - Offset;
394 assert(BytesWritten <= EltSize && "Not indexing into this element?");
395 if (BytesWritten >= BytesLeft)
Chris Lattner67058832012-01-25 06:48:06 +0000396 return true;
Duncan Sands0b875a02012-07-25 09:14:54 +0000397
Chris Lattner67058832012-01-25 06:48:06 +0000398 Offset = 0;
Duncan Sands0b875a02012-07-25 09:14:54 +0000399 BytesLeft -= BytesWritten;
400 CurPtr += BytesWritten;
Chris Lattner67058832012-01-25 06:48:06 +0000401 }
402 return true;
403 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000404
David Majnemer90a97042016-07-13 04:22:12 +0000405 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Anders Carlssonecf8e152011-02-06 20:22:49 +0000406 if (CE->getOpcode() == Instruction::IntToPtr &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000407 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000408 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000409 BytesLeft, DL);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000410 }
Anders Carlssond21b06a2011-02-06 20:11:56 +0000411 }
412
Chris Lattnered00b802009-10-23 06:23:49 +0000413 // Otherwise, unknown initializer type.
414 return false;
415}
416
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000417Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
418 const DataLayout &DL) {
David Majnemer90a97042016-07-13 04:22:12 +0000419 auto *PTy = cast<PointerType>(C->getType());
420 auto *IntType = dyn_cast<IntegerType>(LoadTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000421
Chris Lattnered00b802009-10-23 06:23:49 +0000422 // If this isn't an integer load we can't fold it directly.
423 if (!IntType) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000424 unsigned AS = PTy->getAddressSpace();
425
Chris Lattnered00b802009-10-23 06:23:49 +0000426 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattnerccf1e842009-10-23 06:57:37 +0000427 // and then bitcast the result. This can be useful for union cases. Note
428 // that address spaces don't matter here since we're not going to result in
429 // an actual new load.
Chris Lattner229907c2011-07-18 04:54:35 +0000430 Type *MapTy;
Owen Andersond4ebfd82013-02-06 22:43:31 +0000431 if (LoadTy->isHalfTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000432 MapTy = Type::getInt16Ty(C->getContext());
Owen Andersond4ebfd82013-02-06 22:43:31 +0000433 else if (LoadTy->isFloatTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000434 MapTy = Type::getInt32Ty(C->getContext());
Chris Lattnerccf1e842009-10-23 06:57:37 +0000435 else if (LoadTy->isDoubleTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000436 MapTy = Type::getInt64Ty(C->getContext());
Duncan Sands19d0b472010-02-16 11:11:14 +0000437 else if (LoadTy->isVectorTy()) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000438 MapTy = PointerType::getIntNTy(C->getContext(),
439 DL.getTypeAllocSizeInBits(LoadTy));
Chris Lattnerccf1e842009-10-23 06:57:37 +0000440 } else
Craig Topper9f008862014-04-15 04:59:12 +0000441 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000442
Eduard Burtescu14239212016-01-22 01:17:26 +0000443 C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
444 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000445 return FoldBitCast(Res, LoadTy, DL);
Craig Topper9f008862014-04-15 04:59:12 +0000446 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000447 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000448
Chris Lattnered00b802009-10-23 06:23:49 +0000449 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Matt Arsenault8c789092013-08-12 23:15:58 +0000450 if (BytesLoaded > 32 || BytesLoaded == 0)
Craig Topper9f008862014-04-15 04:59:12 +0000451 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000452
Chris Lattnered00b802009-10-23 06:23:49 +0000453 GlobalValue *GVal;
David Majnemerf89660a2016-07-13 23:33:07 +0000454 APInt OffsetAI;
455 if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000456 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000457
David Majnemer90a97042016-07-13 04:22:12 +0000458 auto *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattner3db7bd22009-10-24 05:27:19 +0000459 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnered00b802009-10-23 06:23:49 +0000460 !GV->getInitializer()->getType()->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000461 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000462
David Majnemerf89660a2016-07-13 23:33:07 +0000463 int64_t Offset = OffsetAI.getSExtValue();
464 int64_t InitializerSize = DL.getTypeAllocSize(GV->getInitializer()->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000465
Chris Lattnered00b802009-10-23 06:23:49 +0000466 // If we're not accessing anything in this constant, the result is undefined.
David Majnemerf89660a2016-07-13 23:33:07 +0000467 if (Offset + BytesLoaded <= 0)
468 return UndefValue::get(IntType);
469
470 // If we're not accessing anything in this constant, the result is undefined.
471 if (Offset >= InitializerSize)
Chris Lattnered00b802009-10-23 06:23:49 +0000472 return UndefValue::get(IntType);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000473
Chris Lattner59f94c02009-10-23 06:50:36 +0000474 unsigned char RawBytes[32] = {0};
David Majnemerf89660a2016-07-13 23:33:07 +0000475 unsigned char *CurPtr = RawBytes;
476 unsigned BytesLeft = BytesLoaded;
477
478 // If we're loading off the beginning of the global, some bytes may be valid.
479 if (Offset < 0) {
480 CurPtr += -Offset;
481 BytesLeft += Offset;
482 Offset = 0;
483 }
484
485 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000486 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000487
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000488 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000489 if (DL.isLittleEndian()) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000490 ResultVal = RawBytes[BytesLoaded - 1];
491 for (unsigned i = 1; i != BytesLoaded; ++i) {
492 ResultVal <<= 8;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000493 ResultVal |= RawBytes[BytesLoaded - 1 - i];
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000494 }
495 } else {
496 ResultVal = RawBytes[0];
497 for (unsigned i = 1; i != BytesLoaded; ++i) {
498 ResultVal <<= 8;
499 ResultVal |= RawBytes[i];
500 }
Chris Lattner59f94c02009-10-23 06:50:36 +0000501 }
Chris Lattnered00b802009-10-23 06:23:49 +0000502
Chris Lattner59f94c02009-10-23 06:50:36 +0000503 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnered00b802009-10-23 06:23:49 +0000504}
505
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000506Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE, Type *DestTy,
507 const DataLayout &DL) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000508 auto *SrcPtr = CE->getOperand(0);
509 auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
510 if (!SrcPtrTy)
Chandler Carrutha0e56952014-05-15 09:56:28 +0000511 return nullptr;
Eduard Burtescu14239212016-01-22 01:17:26 +0000512 Type *SrcTy = SrcPtrTy->getPointerElementType();
Chandler Carrutha0e56952014-05-15 09:56:28 +0000513
Eduard Burtescu14239212016-01-22 01:17:26 +0000514 Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
Chandler Carrutha0e56952014-05-15 09:56:28 +0000515 if (!C)
516 return nullptr;
517
518 do {
519 Type *SrcTy = C->getType();
520
521 // If the type sizes are the same and a cast is legal, just directly
522 // cast the constant.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000523 if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
Chandler Carrutha0e56952014-05-15 09:56:28 +0000524 Instruction::CastOps Cast = Instruction::BitCast;
525 // If we are going from a pointer to int or vice versa, we spell the cast
526 // differently.
527 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
528 Cast = Instruction::IntToPtr;
529 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
530 Cast = Instruction::PtrToInt;
531
532 if (CastInst::castIsValid(Cast, C, DestTy))
533 return ConstantExpr::getCast(Cast, C, DestTy);
534 }
535
536 // If this isn't an aggregate type, there is nothing we can do to drill down
537 // and find a bitcastable constant.
538 if (!SrcTy->isAggregateType())
539 return nullptr;
540
541 // We're simulating a load through a pointer that was bitcast to point to
542 // a different type, so we can try to walk down through the initial
543 // elements of an aggregate to see if some part of th e aggregate is
544 // castable to implement the "load" semantic model.
545 C = C->getAggregateElement(0u);
546 } while (C);
547
548 return nullptr;
549}
550
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000551} // end anonymous namespace
552
Eduard Burtescu14239212016-01-22 01:17:26 +0000553Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000554 const DataLayout &DL) {
Chris Lattner1664a4f2009-10-22 06:25:11 +0000555 // First, try the easy cases:
David Majnemer90a97042016-07-13 04:22:12 +0000556 if (auto *GV = dyn_cast<GlobalVariable>(C))
Chris Lattner1664a4f2009-10-22 06:25:11 +0000557 if (GV->isConstant() && GV->hasDefinitiveInitializer())
558 return GV->getInitializer();
559
David Majnemered9abe12015-07-22 22:29:30 +0000560 if (auto *GA = dyn_cast<GlobalAlias>(C))
Sanjoy Das5ce32722016-04-08 00:48:30 +0000561 if (GA->getAliasee() && !GA->isInterposable())
Eduard Burtescu14239212016-01-22 01:17:26 +0000562 return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
David Majnemered9abe12015-07-22 22:29:30 +0000563
Chris Lattnercf7e8942009-10-22 06:44:07 +0000564 // If the loaded value isn't a constant expr, we can't handle it.
David Majnemer90a97042016-07-13 04:22:12 +0000565 auto *CE = dyn_cast<ConstantExpr>(C);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000566 if (!CE)
Craig Topper9f008862014-04-15 04:59:12 +0000567 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000568
Chris Lattnercf7e8942009-10-22 06:44:07 +0000569 if (CE->getOpcode() == Instruction::GetElementPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000570 if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000571 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000572 if (Constant *V =
Chris Lattnercf7e8942009-10-22 06:44:07 +0000573 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
574 return V;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000575 }
576 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000577 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000578
Chandler Carrutha0e56952014-05-15 09:56:28 +0000579 if (CE->getOpcode() == Instruction::BitCast)
Eduard Burtescu14239212016-01-22 01:17:26 +0000580 if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, Ty, DL))
Chandler Carrutha0e56952014-05-15 09:56:28 +0000581 return LoadedC;
582
Chris Lattnercf7e8942009-10-22 06:44:07 +0000583 // Instead of loading constant c string, use corresponding integer value
584 // directly if string length is small enough.
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000585 StringRef Str;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000586 if (getConstantStringInfo(CE, Str) && !Str.empty()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000587 size_t StrLen = Str.size();
Chris Lattnered00b802009-10-23 06:23:49 +0000588 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000589 // Replace load with immediate integer if the result is an integer or fp
590 // value.
591 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
Chandler Carruth57041d82010-07-12 06:47:05 +0000592 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
Chris Lattnered00b802009-10-23 06:23:49 +0000593 APInt StrVal(NumBits, 0);
594 APInt SingleChar(NumBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000595 if (DL.isLittleEndian()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000596 for (unsigned char C : reverse(Str.bytes())) {
597 SingleChar = static_cast<uint64_t>(C);
Chris Lattner51d2f702009-10-22 06:38:35 +0000598 StrVal = (StrVal << 8) | SingleChar;
599 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000600 } else {
David Majnemere61e4bf2016-06-21 05:10:24 +0000601 for (unsigned char C : Str.bytes()) {
602 SingleChar = static_cast<uint64_t>(C);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000603 StrVal = (StrVal << 8) | SingleChar;
604 }
605 // Append NULL at the end.
606 SingleChar = 0;
607 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner51d2f702009-10-22 06:38:35 +0000608 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000609
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000610 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
611 if (Ty->isFloatingPointTy())
612 Res = ConstantExpr::getBitCast(Res, Ty);
613 return Res;
Chris Lattner51d2f702009-10-22 06:38:35 +0000614 }
Chris Lattner1664a4f2009-10-22 06:25:11 +0000615 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000616
Chris Lattnercf7e8942009-10-22 06:44:07 +0000617 // If this load comes from anywhere in a constant global, and if the global
618 // is all undef or zero, we know what it loads.
David Majnemer90a97042016-07-13 04:22:12 +0000619 if (auto *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000620 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000621 if (GV->getInitializer()->isNullValue())
Eduard Burtescu14239212016-01-22 01:17:26 +0000622 return Constant::getNullValue(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000623 if (isa<UndefValue>(GV->getInitializer()))
Eduard Burtescu14239212016-01-22 01:17:26 +0000624 return UndefValue::get(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000625 }
626 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000627
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000628 // Try hard to fold loads from bitcasted strange and non-type-safe things.
Eduard Burtescu14239212016-01-22 01:17:26 +0000629 return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
Chris Lattner1664a4f2009-10-22 06:25:11 +0000630}
631
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000632namespace {
633
634Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) {
Craig Topper9f008862014-04-15 04:59:12 +0000635 if (LI->isVolatile()) return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000636
David Majnemer90a97042016-07-13 04:22:12 +0000637 if (auto *C = dyn_cast<Constant>(LI->getOperand(0)))
Eduard Burtescu14239212016-01-22 01:17:26 +0000638 return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000639
Craig Topper9f008862014-04-15 04:59:12 +0000640 return nullptr;
Chris Lattner1664a4f2009-10-22 06:25:11 +0000641}
Chris Lattner44d68b92007-01-31 00:51:48 +0000642
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000643/// One of Op0/Op1 is a constant expression.
Nick Lewyckye88d3882008-12-15 01:35:36 +0000644/// Attempt to symbolically evaluate the result of a binary operator merging
Nick Lewycky06417742013-02-14 03:23:37 +0000645/// these together. If target data info is available, it is provided as DL,
646/// otherwise DL is null.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000647Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
648 const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000649 // SROA
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000650
Chris Lattner44d68b92007-01-31 00:51:48 +0000651 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
652 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
653 // bits.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000654
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000655 if (Opc == Instruction::And) {
656 unsigned BitWidth = DL.getTypeSizeInBits(Op0->getType()->getScalarType());
Nick Lewycky06417742013-02-14 03:23:37 +0000657 APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
658 APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
Jay Foada0653a32014-05-14 21:14:37 +0000659 computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
660 computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
Nick Lewycky06417742013-02-14 03:23:37 +0000661 if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
662 // All the bits of Op0 that the 'and' could be masking are already zero.
663 return Op0;
664 }
665 if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
666 // All the bits of Op1 that the 'and' could be masking are already zero.
667 return Op1;
668 }
669
670 APInt KnownZero = KnownZero0 | KnownZero1;
671 APInt KnownOne = KnownOne0 & KnownOne1;
672 if ((KnownZero | KnownOne).isAllOnesValue()) {
673 return ConstantInt::get(Op0->getType(), KnownOne);
674 }
675 }
676
Chris Lattner44d68b92007-01-31 00:51:48 +0000677 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
678 // constant. This happens frequently when iterating over a global array.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000679 if (Opc == Instruction::Sub) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000680 GlobalValue *GV1, *GV2;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000681 APInt Offs1, Offs2;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000682
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000683 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
684 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
685 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
Matt Arsenaultbed5bf22013-09-12 01:07:58 +0000686
Chris Lattner44d68b92007-01-31 00:51:48 +0000687 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Benjamin Kramera5a9ec52013-02-05 19:04:36 +0000688 // PtrToInt may change the bitwidth so we have convert to the right size
689 // first.
690 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
691 Offs2.zextOrTrunc(OpSize));
Chris Lattner44d68b92007-01-31 00:51:48 +0000692 }
693 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000694
Craig Topper9f008862014-04-15 04:59:12 +0000695 return nullptr;
Chris Lattner44d68b92007-01-31 00:51:48 +0000696}
697
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000698/// If array indices are not pointer-sized integers, explicitly cast them so
699/// that they aren't implicitly casted by the getelementptr.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000700Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
701 Type *ResultTy, const DataLayout &DL,
702 const TargetLibraryInfo *TLI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000703 Type *IntPtrTy = DL.getIntPtrType(ResultTy);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000704
705 bool Any = false;
706 SmallVector<Constant*, 32> NewIdxs;
Jay Foadf4b14a22011-07-19 13:32:40 +0000707 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000708 if ((i == 1 ||
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000709 !isa<StructType>(GetElementPtrInst::getIndexedType(SrcElemTy,
David Blaikied288fb82015-03-30 21:41:43 +0000710 Ops.slice(1, i - 1)))) &&
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000711 Ops[i]->getType() != IntPtrTy) {
712 Any = true;
713 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
714 true,
715 IntPtrTy,
716 true),
717 Ops[i], IntPtrTy));
718 } else
719 NewIdxs.push_back(Ops[i]);
720 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000721
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000722 if (!Any)
Craig Topper9f008862014-04-15 04:59:12 +0000723 return nullptr;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000724
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000725 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ops[0], NewIdxs);
David Majnemerd536f232016-07-29 03:27:26 +0000726 if (Constant *Folded = ConstantFoldConstant(C, DL, TLI))
727 C = Folded;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000728
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000729 return C;
730}
731
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000732/// Strip the pointer casts, but preserve the address space information.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000733Constant* StripPtrCastKeepAS(Constant* Ptr, Type *&ElemTy) {
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000734 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
David Majnemer90a97042016-07-13 04:22:12 +0000735 auto *OldPtrTy = cast<PointerType>(Ptr->getType());
Rafael Espindola78598d92014-06-04 19:01:48 +0000736 Ptr = Ptr->stripPointerCasts();
David Majnemer90a97042016-07-13 04:22:12 +0000737 auto *NewPtrTy = cast<PointerType>(Ptr->getType());
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000738
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000739 ElemTy = NewPtrTy->getPointerElementType();
740
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000741 // Preserve the address space number of the pointer.
742 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000743 NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000744 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000745 }
746 return Ptr;
747}
748
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000749/// If we can symbolically evaluate the GEP constant expression, do so.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000750Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
751 ArrayRef<Constant *> Ops,
752 const DataLayout &DL,
753 const TargetLibraryInfo *TLI) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000754 Type *SrcElemTy = GEP->getSourceElementType();
755 Type *ResElemTy = GEP->getResultElementType();
756 Type *ResTy = GEP->getType();
757 if (!SrcElemTy->isSized())
758 return nullptr;
759
760 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy, DL, TLI))
761 return C;
762
Chris Lattner44d68b92007-01-31 00:51:48 +0000763 Constant *Ptr = Ops[0];
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000764 if (!Ptr->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +0000765 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000766
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000767 Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
Chris Lattnerf4b42f52008-05-08 04:54:43 +0000768
769 // If this is a constant expr gep that is effectively computing an
770 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
Jay Foadf4b14a22011-07-19 13:32:40 +0000771 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Chris Lattner5858e092011-01-06 06:19:46 +0000772 if (!isa<ConstantInt>(Ops[i])) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000773
Chris Lattner5858e092011-01-06 06:19:46 +0000774 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
775 // "inttoptr (sub (ptrtoint Ptr), V)"
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000776 if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
David Majnemer90a97042016-07-13 04:22:12 +0000777 auto *CE = dyn_cast<ConstantExpr>(Ops[1]);
Craig Topper9f008862014-04-15 04:59:12 +0000778 assert((!CE || CE->getType() == IntPtrTy) &&
Chris Lattner171608e2011-01-06 22:24:29 +0000779 "CastGEPIndices didn't canonicalize index types!");
Chris Lattner5858e092011-01-06 06:19:46 +0000780 if (CE && CE->getOpcode() == Instruction::Sub &&
Chris Lattner171608e2011-01-06 22:24:29 +0000781 CE->getOperand(0)->isNullValue()) {
Chris Lattner5858e092011-01-06 06:19:46 +0000782 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
783 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000784 Res = ConstantExpr::getIntToPtr(Res, ResTy);
David Majnemerd536f232016-07-29 03:27:26 +0000785 if (auto *FoldedRes = ConstantFoldConstant(Res, DL, TLI))
786 Res = FoldedRes;
Chris Lattner5858e092011-01-06 06:19:46 +0000787 return Res;
788 }
789 }
Craig Topper9f008862014-04-15 04:59:12 +0000790 return nullptr;
Chris Lattner5858e092011-01-06 06:19:46 +0000791 }
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000792
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000793 unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
Jay Foadbf904772011-07-19 14:01:37 +0000794 APInt Offset =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000795 APInt(BitWidth,
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000796 DL.getIndexedOffsetInType(
797 SrcElemTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000798 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000799 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000800
801 // If this is a GEP of a GEP, fold it all into a single GEP.
David Majnemer90a97042016-07-13 04:22:12 +0000802 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000803 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
Duncan Sands8c355062010-03-12 17:55:20 +0000804
805 // Do not try the incorporate the sub-GEP if some index is not a number.
806 bool AllConstantInt = true;
David Majnemer90a97042016-07-13 04:22:12 +0000807 for (Value *NestedOp : NestedOps)
808 if (!isa<ConstantInt>(NestedOp)) {
Duncan Sands8c355062010-03-12 17:55:20 +0000809 AllConstantInt = false;
810 break;
811 }
812 if (!AllConstantInt)
813 break;
814
Dan Gohman474e488c2010-03-10 19:31:51 +0000815 Ptr = cast<Constant>(GEP->getOperand(0));
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000816 SrcElemTy = GEP->getSourceElementType();
817 Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000818 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000819 }
820
Dan Gohman81ce8422009-08-19 18:18:36 +0000821 // If the base value for this address is a literal integer value, fold the
822 // getelementptr to the resulting integer value casted to the pointer type.
Dan Gohmana5ca5782010-03-18 19:34:33 +0000823 APInt BasePtr(BitWidth, 0);
David Majnemer90a97042016-07-13 04:22:12 +0000824 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000825 if (CE->getOpcode() == Instruction::IntToPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000826 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
Jay Foad583abbc2010-12-07 08:25:19 +0000827 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000828 }
829 }
830
Sanjoy Das6fa08aa2016-08-05 19:23:29 +0000831 auto *PTy = cast<PointerType>(Ptr->getType());
832 if ((Ptr->isNullValue() || BasePtr != 0) &&
833 !DL.isNonIntegralPointerType(PTy)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000834 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000835 return ConstantExpr::getIntToPtr(C, ResTy);
Dan Gohman81ce8422009-08-19 18:18:36 +0000836 }
837
838 // Otherwise form a regular getelementptr. Recompute the indices so that
839 // we eliminate over-indexing of the notional static type array bounds.
840 // This makes it easy to determine if the getelementptr is "inbounds".
841 // Also, this helps GlobalOpt do SROA on GlobalVariables.
Sanjoy Das6fa08aa2016-08-05 19:23:29 +0000842 Type *Ty = PTy;
Matt Arsenault7a960a82013-08-20 21:20:04 +0000843 SmallVector<Constant *, 32> NewIdxs;
844
Dan Gohmanc59ba422009-08-19 22:46:59 +0000845 do {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000846 if (!Ty->isStructTy()) {
847 if (Ty->isPointerTy()) {
Chris Lattner77c36d62009-12-03 01:05:45 +0000848 // The only pointer indexing we'll do is on the first index of the GEP.
849 if (!NewIdxs.empty())
850 break;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000851
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000852 Ty = SrcElemTy;
853
Chris Lattner77c36d62009-12-03 01:05:45 +0000854 // Only handle pointers to sized types, not pointers to functions.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000855 if (!Ty->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000856 return nullptr;
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000857 } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) {
858 Ty = ATy->getElementType();
859 } else {
860 // We've reached some non-indexable type.
861 break;
Chris Lattner77c36d62009-12-03 01:05:45 +0000862 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000863
Dan Gohman81ce8422009-08-19 18:18:36 +0000864 // Determine which element of the array the offset points into.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000865 APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
David Majnemer1b3db332016-07-13 05:16:16 +0000866 if (ElemSize == 0) {
Chris Lattner6ce03802010-11-21 08:39:01 +0000867 // The element size is 0. This may be [0 x Ty]*, so just use a zero
Duncan Sands1f86be92010-11-21 12:43:13 +0000868 // index for this level and proceed to the next level to see if it can
869 // accommodate the offset.
Chris Lattner6ce03802010-11-21 08:39:01 +0000870 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
David Majnemer1b3db332016-07-13 05:16:16 +0000871 } else {
Chris Lattner6ce03802010-11-21 08:39:01 +0000872 // The element size is non-zero divide the offset by the element
873 // size (rounding down), to compute the index at this level.
David Majnemer4cff2f82016-07-13 15:53:46 +0000874 bool Overflow;
875 APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow);
876 if (Overflow)
877 break;
Chris Lattner6ce03802010-11-21 08:39:01 +0000878 Offset -= NewIdx * ElemSize;
879 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
880 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000881 } else {
David Majnemer90a97042016-07-13 04:22:12 +0000882 auto *STy = cast<StructType>(Ty);
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000883 // If we end up with an offset that isn't valid for this struct type, we
884 // can't re-form this GEP in a regular form, so bail out. The pointer
885 // operand likely went through casts that are necessary to make the GEP
886 // sensible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000887 const StructLayout &SL = *DL.getStructLayout(STy);
David Majnemer1b3db332016-07-13 05:16:16 +0000888 if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes()))
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000889 break;
890
891 // Determine which field of the struct the offset points into. The
892 // getZExtValue is fine as we've already ensured that the offset is
893 // within the range representable by the StructLayout API.
Dan Gohman23e62c52009-08-21 16:52:54 +0000894 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Chris Lattner46b5c642009-11-06 04:27:31 +0000895 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
896 ElIdx));
Dan Gohman23e62c52009-08-21 16:52:54 +0000897 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohman81ce8422009-08-19 18:18:36 +0000898 Ty = STy->getTypeAtIndex(ElIdx);
Dan Gohman81ce8422009-08-19 18:18:36 +0000899 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000900 } while (Ty != ResElemTy);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000901
902 // If we haven't used up the entire offset by descending the static
903 // type, then the offset is pointing into the middle of an indivisible
904 // member, so we can't simplify it.
905 if (Offset != 0)
Craig Topper9f008862014-04-15 04:59:12 +0000906 return nullptr;
Dan Gohman81ce8422009-08-19 18:18:36 +0000907
Dan Gohman21c62162009-09-11 00:04:14 +0000908 // Create a GEP.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000909 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs);
Matt Arsenault8c789092013-08-12 23:15:58 +0000910 assert(C->getType()->getPointerElementType() == Ty &&
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000911 "Computed GetElementPtr has unexpected type!");
Dan Gohman81ce8422009-08-19 18:18:36 +0000912
Dan Gohmanc59ba422009-08-19 22:46:59 +0000913 // If we ended up indexing a member with a type that doesn't match
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000914 // the type of what the original indices indexed, add a cast.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000915 if (Ty != ResElemTy)
916 C = FoldBitCast(C, ResTy, DL);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000917
918 return C;
Chris Lattner44d68b92007-01-31 00:51:48 +0000919}
920
Manuel Jacobe9024592016-01-21 06:33:22 +0000921/// Attempt to constant fold an instruction with the
922/// specified opcode and operands. If successful, the constant result is
923/// returned, if not, null is returned. Note that this function can fail when
924/// attempting to fold instructions like loads and stores, which have no
925/// constant expression form.
926///
927/// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
928/// information, due to only being passed an opcode and operands. Constant
929/// folding using this function strips this information.
930///
David Majnemera926b3e2016-07-29 03:27:33 +0000931Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000932 ArrayRef<Constant *> Ops,
933 const DataLayout &DL,
934 const TargetLibraryInfo *TLI) {
David Majnemera926b3e2016-07-29 03:27:33 +0000935 Type *DestTy = InstOrCE->getType();
936
Manuel Jacobe9024592016-01-21 06:33:22 +0000937 // Handle easy binops first.
938 if (Instruction::isBinaryOp(Opcode))
939 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
940
941 if (Instruction::isCast(Opcode))
942 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
943
David Majnemer17bdf442016-07-13 03:42:38 +0000944 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000945 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
946 return C;
947
948 return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(),
949 Ops[0], Ops.slice(1));
950 }
951
David Majnemer57b94c82016-07-29 03:27:31 +0000952 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
953 return CE->getWithOperands(Ops);
954
Manuel Jacobe9024592016-01-21 06:33:22 +0000955 switch (Opcode) {
956 default: return nullptr;
957 case Instruction::ICmp:
958 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
959 case Instruction::Call:
David Majnemer90a97042016-07-13 04:22:12 +0000960 if (auto *F = dyn_cast<Function>(Ops.back()))
Manuel Jacobe9024592016-01-21 06:33:22 +0000961 if (canConstantFoldCallTo(F))
962 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
963 return nullptr;
964 case Instruction::Select:
965 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
966 case Instruction::ExtractElement:
967 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
968 case Instruction::InsertElement:
969 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
970 case Instruction::ShuffleVector:
971 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Manuel Jacobe9024592016-01-21 06:33:22 +0000972 }
973}
974
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000975} // end anonymous namespace
Chris Lattner44d68b92007-01-31 00:51:48 +0000976
977//===----------------------------------------------------------------------===//
978// Constant Folding public APIs
979//===----------------------------------------------------------------------===//
980
David Majnemerd536f232016-07-29 03:27:26 +0000981namespace {
982
983Constant *
984ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
985 const TargetLibraryInfo *TLI,
986 SmallDenseMap<Constant *, Constant *> &FoldedOps) {
987 if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
988 return nullptr;
989
990 SmallVector<Constant *, 8> Ops;
991 for (const Use &NewU : C->operands()) {
992 auto *NewC = cast<Constant>(&NewU);
993 // Recursively fold the ConstantExpr's operands. If we have already folded
994 // a ConstantExpr, we don't have to process it again.
995 if (isa<ConstantVector>(NewC) || isa<ConstantExpr>(NewC)) {
996 auto It = FoldedOps.find(NewC);
997 if (It == FoldedOps.end()) {
998 if (auto *FoldedC =
999 ConstantFoldConstantImpl(NewC, DL, TLI, FoldedOps)) {
1000 NewC = FoldedC;
1001 FoldedOps.insert({NewC, FoldedC});
1002 } else {
1003 FoldedOps.insert({NewC, NewC});
1004 }
1005 } else {
1006 NewC = It->second;
1007 }
1008 }
1009 Ops.push_back(NewC);
1010 }
1011
1012 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1013 if (CE->isCompare())
1014 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1015 DL, TLI);
1016
David Majnemera926b3e2016-07-29 03:27:33 +00001017 return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI);
David Majnemerd536f232016-07-29 03:27:26 +00001018 }
1019
1020 assert(isa<ConstantVector>(C));
1021 return ConstantVector::get(Ops);
1022}
1023
1024} // end anonymous namespace
1025
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001026Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001027 const TargetLibraryInfo *TLI) {
Duncan Sands763dec02010-11-23 10:16:18 +00001028 // Handle PHI nodes quickly here...
David Majnemer90a97042016-07-13 04:22:12 +00001029 if (auto *PN = dyn_cast<PHINode>(I)) {
Craig Topper9f008862014-04-15 04:59:12 +00001030 Constant *CommonValue = nullptr;
John Criswell970af112005-10-27 16:00:10 +00001031
David Majnemerd536f232016-07-29 03:27:26 +00001032 SmallDenseMap<Constant *, Constant *> FoldedOps;
Pete Cooper833f34d2015-05-12 20:05:31 +00001033 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands763dec02010-11-23 10:16:18 +00001034 // If the incoming value is undef then skip it. Note that while we could
1035 // skip the value if it is equal to the phi node itself we choose not to
1036 // because that would break the rule that constant folding only applies if
1037 // all operands are constants.
1038 if (isa<UndefValue>(Incoming))
Duncan Sands1d27f0122010-11-14 12:53:18 +00001039 continue;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001040 // If the incoming value is not a constant, then give up.
David Majnemer90a97042016-07-13 04:22:12 +00001041 auto *C = dyn_cast<Constant>(Incoming);
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001042 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00001043 return nullptr;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001044 // Fold the PHI's operands.
David Majnemerd536f232016-07-29 03:27:26 +00001045 if (auto *FoldedC = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps))
1046 C = FoldedC;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001047 // If the incoming value is a different constant to
1048 // the one we saw previously, then give up.
1049 if (CommonValue && C != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00001050 return nullptr;
Duncan Sands1d27f0122010-11-14 12:53:18 +00001051 CommonValue = C;
1052 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001053
Duncan Sands1d27f0122010-11-14 12:53:18 +00001054 // If we reach here, all incoming values are the same constant or undef.
1055 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
Chris Lattner2ae054a2007-01-30 23:45:45 +00001056 }
1057
1058 // Scan the operand list, checking to see if they are all constants, if so,
Manuel Jacobe9024592016-01-21 06:33:22 +00001059 // hand off to ConstantFoldInstOperandsImpl.
Fiona Glaser2e5c0c22016-03-13 05:36:15 +00001060 if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1061 return nullptr;
Chris Lattner2ae054a2007-01-30 23:45:45 +00001062
David Majnemerd536f232016-07-29 03:27:26 +00001063 SmallDenseMap<Constant *, Constant *> FoldedOps;
Fiona Glaser2e5c0c22016-03-13 05:36:15 +00001064 SmallVector<Constant *, 8> Ops;
David Majnemer90a97042016-07-13 04:22:12 +00001065 for (const Use &OpU : I->operands()) {
1066 auto *Op = cast<Constant>(&OpU);
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001067 // Fold the Instruction's operands.
David Majnemerd536f232016-07-29 03:27:26 +00001068 if (auto *FoldedOp = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps))
1069 Op = FoldedOp;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001070
1071 Ops.push_back(Op);
1072 }
1073
David Majnemer90a97042016-07-13 04:22:12 +00001074 if (const auto *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001075 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001076 DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001077
David Majnemer90a97042016-07-13 04:22:12 +00001078 if (const auto *LI = dyn_cast<LoadInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001079 return ConstantFoldLoadInst(LI, DL);
Frits van Bommela98214d2010-11-29 20:36:52 +00001080
David Majnemer90a97042016-07-13 04:22:12 +00001081 if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001082 return ConstantExpr::getInsertValue(
1083 cast<Constant>(IVI->getAggregateOperand()),
1084 cast<Constant>(IVI->getInsertedValueOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001085 IVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001086 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001087
David Majnemer90a97042016-07-13 04:22:12 +00001088 if (auto *EVI = dyn_cast<ExtractValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001089 return ConstantExpr::getExtractValue(
1090 cast<Constant>(EVI->getAggregateOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001091 EVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001092 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001093
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001094 return ConstantFoldInstOperands(I, Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001095}
1096
David Majnemerd536f232016-07-29 03:27:26 +00001097Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL,
1098 const TargetLibraryInfo *TLI) {
1099 SmallDenseMap<Constant *, Constant *> FoldedOps;
1100 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +00001101}
1102
Manuel Jacobe9024592016-01-21 06:33:22 +00001103Constant *llvm::ConstantFoldInstOperands(Instruction *I,
Jay Foadf4b14a22011-07-19 13:32:40 +00001104 ArrayRef<Constant *> Ops,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001105 const DataLayout &DL,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001106 const TargetLibraryInfo *TLI) {
David Majnemera926b3e2016-07-29 03:27:33 +00001107 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001108}
1109
Chris Lattnerd2265b42007-12-10 22:53:04 +00001110Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001111 Constant *Ops0, Constant *Ops1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001112 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001113 const TargetLibraryInfo *TLI) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001114 // fold: icmp (inttoptr x), null -> icmp x, 0
1115 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001116 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd2265b42007-12-10 22:53:04 +00001117 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1118 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001119 // FIXME: The following comment is out of data and the DataLayout is here now.
1120 // ConstantExpr::getCompare cannot do this, because it doesn't have DL
Chris Lattnerd2265b42007-12-10 22:53:04 +00001121 // around to know if bit truncation is happening.
David Majnemer90a97042016-07-13 04:22:12 +00001122 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001123 if (Ops1->isNullValue()) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001124 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001125 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Chris Lattnerd2265b42007-12-10 22:53:04 +00001126 // Convert the integer value to the right size to ensure we get the
1127 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001128 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd2265b42007-12-10 22:53:04 +00001129 IntPtrTy, false);
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001130 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001131 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001132 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001133
Chris Lattnerd2265b42007-12-10 22:53:04 +00001134 // Only do this transformation if the int is intptrty in size, otherwise
1135 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001136 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001137 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001138 if (CE0->getType() == IntPtrTy) {
1139 Constant *C = CE0->getOperand(0);
1140 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001141 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001142 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001143 }
1144 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001145
David Majnemer90a97042016-07-13 04:22:12 +00001146 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001147 if (CE0->getOpcode() == CE1->getOpcode()) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001148 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001149 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001150
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001151 // Convert the integer value to the right size to ensure we get the
1152 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001153 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001154 IntPtrTy, false);
Owen Anderson487375e2009-07-29 18:55:55 +00001155 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001156 IntPtrTy, false);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001157 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001158 }
1159
Chandler Carruth7ec50852012-11-01 08:07:29 +00001160 // Only do this transformation if the int is intptrty in size, otherwise
1161 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001162 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001163 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001164 if (CE0->getType() == IntPtrTy &&
1165 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001166 return ConstantFoldCompareInstOperands(
1167 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001168 }
1169 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001170 }
1171 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001172
Chris Lattner8fb74c62010-01-02 01:22:23 +00001173 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1174 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1175 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1176 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001177 Constant *LHS = ConstantFoldCompareInstOperands(
1178 Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1179 Constant *RHS = ConstantFoldCompareInstOperands(
1180 Predicate, CE0->getOperand(1), Ops1, DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001181 unsigned OpC =
Chris Lattner8fb74c62010-01-02 01:22:23 +00001182 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
Manuel Jacoba61ca372016-01-21 06:26:35 +00001183 return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
Chris Lattner8fb74c62010-01-02 01:22:23 +00001184 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001185 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001186
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001187 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001188}
1189
Manuel Jacoba61ca372016-01-21 06:26:35 +00001190Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1191 Constant *RHS,
1192 const DataLayout &DL) {
1193 assert(Instruction::isBinaryOp(Opcode));
1194 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1195 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1196 return C;
1197
1198 return ConstantExpr::get(Opcode, LHS, RHS);
1199}
Chris Lattnerd2265b42007-12-10 22:53:04 +00001200
Manuel Jacob925d0292016-01-21 06:31:08 +00001201Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1202 Type *DestTy, const DataLayout &DL) {
1203 assert(Instruction::isCast(Opcode));
1204 switch (Opcode) {
1205 default:
1206 llvm_unreachable("Missing case");
1207 case Instruction::PtrToInt:
1208 // If the input is a inttoptr, eliminate the pair. This requires knowing
1209 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001210 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001211 if (CE->getOpcode() == Instruction::IntToPtr) {
1212 Constant *Input = CE->getOperand(0);
1213 unsigned InWidth = Input->getType()->getScalarSizeInBits();
1214 unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1215 if (PtrWidth < InWidth) {
1216 Constant *Mask =
1217 ConstantInt::get(CE->getContext(),
1218 APInt::getLowBitsSet(InWidth, PtrWidth));
1219 Input = ConstantExpr::getAnd(Input, Mask);
1220 }
1221 // Do a zext or trunc to get to the dest size.
1222 return ConstantExpr::getIntegerCast(Input, DestTy, false);
1223 }
1224 }
1225 return ConstantExpr::getCast(Opcode, C, DestTy);
1226 case Instruction::IntToPtr:
1227 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1228 // the int size is >= the ptr size and the address spaces are the same.
1229 // This requires knowing the width of a pointer, so it can't be done in
1230 // ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001231 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001232 if (CE->getOpcode() == Instruction::PtrToInt) {
1233 Constant *SrcPtr = CE->getOperand(0);
1234 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1235 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1236
1237 if (MidIntSize >= SrcPtrSize) {
1238 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1239 if (SrcAS == DestTy->getPointerAddressSpace())
1240 return FoldBitCast(CE->getOperand(0), DestTy, DL);
1241 }
1242 }
1243 }
1244
1245 return ConstantExpr::getCast(Opcode, C, DestTy);
1246 case Instruction::Trunc:
1247 case Instruction::ZExt:
1248 case Instruction::SExt:
1249 case Instruction::FPTrunc:
1250 case Instruction::FPExt:
1251 case Instruction::UIToFP:
1252 case Instruction::SIToFP:
1253 case Instruction::FPToUI:
1254 case Instruction::FPToSI:
1255 case Instruction::AddrSpaceCast:
1256 return ConstantExpr::getCast(Opcode, C, DestTy);
1257 case Instruction::BitCast:
1258 return FoldBitCast(C, DestTy, DL);
1259 }
1260}
1261
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001262Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmane525d9d2009-10-05 16:36:26 +00001263 ConstantExpr *CE) {
Chris Lattnerf488b352012-01-24 05:43:50 +00001264 if (!CE->getOperand(1)->isNullValue())
Craig Topper9f008862014-04-15 04:59:12 +00001265 return nullptr; // Do not allow stepping over the value!
Chris Lattner67058832012-01-25 06:48:06 +00001266
1267 // Loop over all of the operands, tracking down which value we are
1268 // addressing.
1269 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1270 C = C->getAggregateElement(CE->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00001271 if (!C)
1272 return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00001273 }
1274 return C;
Chris Lattnerf488b352012-01-24 05:43:50 +00001275}
1276
David Majnemer90a97042016-07-13 04:22:12 +00001277Constant *
1278llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1279 ArrayRef<Constant *> Indices) {
Chris Lattner2ae054a2007-01-30 23:45:45 +00001280 // Loop over all of the operands, tracking down which value we are
Chris Lattnerf488b352012-01-24 05:43:50 +00001281 // addressing.
David Majnemer90a97042016-07-13 04:22:12 +00001282 for (Constant *Index : Indices) {
1283 C = C->getAggregateElement(Index);
Craig Topper9f008862014-04-15 04:59:12 +00001284 if (!C)
1285 return nullptr;
Chris Lattnerf488b352012-01-24 05:43:50 +00001286 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001287 return C;
1288}
1289
Chris Lattner2ae054a2007-01-30 23:45:45 +00001290//===----------------------------------------------------------------------===//
1291// Constant Folding for Calls
1292//
John Criswell970af112005-10-27 16:00:10 +00001293
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001294bool llvm::canConstantFoldCallTo(const Function *F) {
John Criswell970af112005-10-27 16:00:10 +00001295 switch (F->getIntrinsicID()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001296 case Intrinsic::fabs:
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001297 case Intrinsic::minnum:
1298 case Intrinsic::maxnum:
Owen Andersond4ebfd82013-02-06 22:43:31 +00001299 case Intrinsic::log:
1300 case Intrinsic::log2:
1301 case Intrinsic::log10:
1302 case Intrinsic::exp:
1303 case Intrinsic::exp2:
1304 case Intrinsic::floor:
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001305 case Intrinsic::ceil:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001306 case Intrinsic::sqrt:
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001307 case Intrinsic::sin:
1308 case Intrinsic::cos:
Karthik Bhatd818e382015-07-21 08:52:23 +00001309 case Intrinsic::trunc:
1310 case Intrinsic::rint:
1311 case Intrinsic::nearbyint:
Chad Rosier0155a632011-12-03 00:00:03 +00001312 case Intrinsic::pow:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001313 case Intrinsic::powi:
Reid Spencer6bba6c82007-04-01 07:35:23 +00001314 case Intrinsic::bswap:
1315 case Intrinsic::ctpop:
1316 case Intrinsic::ctlz:
1317 case Intrinsic::cttz:
Matt Arsenault83778582014-03-05 00:02:00 +00001318 case Intrinsic::fma:
1319 case Intrinsic::fmuladd:
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001320 case Intrinsic::copysign:
Karthik Bhatb67688a2014-03-07 04:36:21 +00001321 case Intrinsic::round:
David Majnemer7f781ab2016-07-14 00:29:50 +00001322 case Intrinsic::masked_load:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001323 case Intrinsic::sadd_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001324 case Intrinsic::uadd_with_overflow:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001325 case Intrinsic::ssub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001326 case Intrinsic::usub_with_overflow:
Chris Lattner698661c2010-10-14 00:05:07 +00001327 case Intrinsic::smul_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001328 case Intrinsic::umul_with_overflow:
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001329 case Intrinsic::convert_from_fp16:
1330 case Intrinsic::convert_to_fp16:
Matt Arsenault155dda92016-03-21 15:00:35 +00001331 case Intrinsic::bitreverse:
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001332 case Intrinsic::x86_sse_cvtss2si:
1333 case Intrinsic::x86_sse_cvtss2si64:
1334 case Intrinsic::x86_sse_cvttss2si:
1335 case Intrinsic::x86_sse_cvttss2si64:
1336 case Intrinsic::x86_sse2_cvtsd2si:
1337 case Intrinsic::x86_sse2_cvtsd2si64:
1338 case Intrinsic::x86_sse2_cvttsd2si:
1339 case Intrinsic::x86_sse2_cvttsd2si64:
John Criswell970af112005-10-27 16:00:10 +00001340 return true;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001341 default:
1342 return false;
1343 case 0: break;
John Criswell970af112005-10-27 16:00:10 +00001344 }
1345
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001346 if (!F->hasName())
1347 return false;
Daniel Dunbarca414c72009-07-26 08:34:35 +00001348 StringRef Name = F->getName();
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001349
Chris Lattner785f9982007-08-08 06:55:43 +00001350 // In these cases, the check of the length is required. We don't want to
1351 // return true for a name like "cos\0blah" which strcmp would return equal to
1352 // "cos", but has length 8.
Daniel Dunbarca414c72009-07-26 08:34:35 +00001353 switch (Name[0]) {
Erik Schnetter5e93e282015-08-27 19:56:57 +00001354 default:
1355 return false;
Chris Lattner785f9982007-08-08 06:55:43 +00001356 case 'a':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001357 return Name == "acos" || Name == "asin" || Name == "atan" ||
1358 Name == "atan2" || Name == "acosf" || Name == "asinf" ||
1359 Name == "atanf" || Name == "atan2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001360 case 'c':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001361 return Name == "ceil" || Name == "cos" || Name == "cosh" ||
1362 Name == "ceilf" || Name == "cosf" || Name == "coshf";
Chris Lattner785f9982007-08-08 06:55:43 +00001363 case 'e':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001364 return Name == "exp" || Name == "exp2" || Name == "expf" || Name == "exp2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001365 case 'f':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001366 return Name == "fabs" || Name == "floor" || Name == "fmod" ||
1367 Name == "fabsf" || Name == "floorf" || Name == "fmodf";
Chris Lattner785f9982007-08-08 06:55:43 +00001368 case 'l':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001369 return Name == "log" || Name == "log10" || Name == "logf" ||
1370 Name == "log10f";
Chris Lattner785f9982007-08-08 06:55:43 +00001371 case 'p':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001372 return Name == "pow" || Name == "powf";
Chris Lattner785f9982007-08-08 06:55:43 +00001373 case 's':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001374 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
Erik Schnetter5e93e282015-08-27 19:56:57 +00001375 Name == "sinf" || Name == "sinhf" || Name == "sqrtf";
Chris Lattner785f9982007-08-08 06:55:43 +00001376 case 't':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001377 return Name == "tan" || Name == "tanh" || Name == "tanf" || Name == "tanhf";
John Criswell970af112005-10-27 16:00:10 +00001378 }
1379}
1380
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001381namespace {
1382
1383Constant *GetConstantFoldFPValue(double V, Type *Ty) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001384 if (Ty->isHalfTy()) {
1385 APFloat APF(V);
1386 bool unused;
1387 APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1388 return ConstantFP::get(Ty->getContext(), APF);
1389 }
Chris Lattner351534f2009-10-05 05:06:24 +00001390 if (Ty->isFloatTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001391 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
Chris Lattner351534f2009-10-05 05:06:24 +00001392 if (Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001393 return ConstantFP::get(Ty->getContext(), APFloat(V));
Owen Andersond4ebfd82013-02-06 22:43:31 +00001394 llvm_unreachable("Can only constant fold half/float/double");
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001395}
1396
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001397/// Clear the floating-point exception state.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001398inline void llvm_fenv_clearexcept() {
Alp Toker51420a82014-06-09 19:00:52 +00001399#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001400 feclearexcept(FE_ALL_EXCEPT);
1401#endif
1402 errno = 0;
1403}
1404
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001405/// Test if a floating-point exception was raised.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001406inline bool llvm_fenv_testexcept() {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001407 int errno_val = errno;
1408 if (errno_val == ERANGE || errno_val == EDOM)
1409 return true;
Alp Toker51420a82014-06-09 19:00:52 +00001410#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001411 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1412 return true;
1413#endif
1414 return false;
1415}
Alp Tokerc817d6a2014-06-09 18:28:53 +00001416
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001417Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001418 llvm_fenv_clearexcept();
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001419 V = NativeFP(V);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001420 if (llvm_fenv_testexcept()) {
1421 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001422 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001423 }
1424
1425 return GetConstantFoldFPValue(V, Ty);
John Criswell970af112005-10-27 16:00:10 +00001426}
1427
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001428Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1429 double W, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001430 llvm_fenv_clearexcept();
Dan Gohman72efc042007-07-16 15:26:22 +00001431 V = NativeFP(V, W);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001432 if (llvm_fenv_testexcept()) {
1433 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001434 return nullptr;
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001435 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001436
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001437 return GetConstantFoldFPValue(V, Ty);
Dan Gohman72efc042007-07-16 15:26:22 +00001438}
1439
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001440/// Attempt to fold an SSE floating point to integer conversion of a constant
1441/// floating point. If roundTowardZero is false, the default IEEE rounding is
1442/// used (toward nearest, ties to even). This matches the behavior of the
1443/// non-truncating SSE instructions in the default rounding mode. The desired
1444/// integer type Ty is used to select how many bits are available for the
1445/// result. Returns null if the conversion cannot be performed, otherwise
1446/// returns the Constant value resulting from the conversion.
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001447Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
1448 Type *Ty) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001449 // All of these conversion intrinsics form an integer of at most 64bits.
Matt Arsenault8c789092013-08-12 23:15:58 +00001450 unsigned ResultWidth = Ty->getIntegerBitWidth();
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001451 assert(ResultWidth <= 64 &&
1452 "Can only constant fold conversions to 64 and 32 bit ints");
1453
1454 uint64_t UIntVal;
1455 bool isExact = false;
1456 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1457 : APFloat::rmNearestTiesToEven;
1458 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1459 /*isSigned=*/true, mode,
1460 &isExact);
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001461 if (status != APFloat::opOK &&
1462 (!roundTowardZero || status != APFloat::opInexact))
Craig Topper9f008862014-04-15 04:59:12 +00001463 return nullptr;
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001464 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1465}
1466
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001467double getValueAsDouble(ConstantFP *Op) {
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001468 Type *Ty = Op->getType();
1469
1470 if (Ty->isFloatTy())
1471 return Op->getValueAPF().convertToFloat();
1472
1473 if (Ty->isDoubleTy())
1474 return Op->getValueAPF().convertToDouble();
1475
1476 bool unused;
1477 APFloat APF = Op->getValueAPF();
1478 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1479 return APF.convertToDouble();
1480}
1481
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001482Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty,
1483 ArrayRef<Constant *> Operands,
1484 const TargetLibraryInfo *TLI) {
Jay Foadf4b14a22011-07-19 13:32:40 +00001485 if (Operands.size() == 1) {
Sanjoy Das87b9e1b2016-04-08 18:21:11 +00001486 if (isa<UndefValue>(Operands[0])) {
1487 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN
1488 if (IntrinsicID == Intrinsic::cos)
1489 return Constant::getNullValue(Ty);
1490 }
David Majnemer90a97042016-07-13 04:22:12 +00001491 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001492 if (IntrinsicID == Intrinsic::convert_to_fp16) {
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001493 APFloat Val(Op->getValueAPF());
1494
1495 bool lost = false;
1496 Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1497
Benjamin Kramer061d1472014-03-05 19:41:48 +00001498 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001499 }
1500
Owen Andersond4ebfd82013-02-06 22:43:31 +00001501 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001502 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001503
Karthik Bhatb67688a2014-03-07 04:36:21 +00001504 if (IntrinsicID == Intrinsic::round) {
1505 APFloat V = Op->getValueAPF();
1506 V.roundToIntegral(APFloat::rmNearestTiesToAway);
1507 return ConstantFP::get(Ty->getContext(), V);
1508 }
1509
Karthik Bhatd818e382015-07-21 08:52:23 +00001510 if (IntrinsicID == Intrinsic::floor) {
1511 APFloat V = Op->getValueAPF();
1512 V.roundToIntegral(APFloat::rmTowardNegative);
1513 return ConstantFP::get(Ty->getContext(), V);
1514 }
1515
1516 if (IntrinsicID == Intrinsic::ceil) {
1517 APFloat V = Op->getValueAPF();
1518 V.roundToIntegral(APFloat::rmTowardPositive);
1519 return ConstantFP::get(Ty->getContext(), V);
1520 }
1521
1522 if (IntrinsicID == Intrinsic::trunc) {
1523 APFloat V = Op->getValueAPF();
1524 V.roundToIntegral(APFloat::rmTowardZero);
1525 return ConstantFP::get(Ty->getContext(), V);
1526 }
1527
1528 if (IntrinsicID == Intrinsic::rint) {
1529 APFloat V = Op->getValueAPF();
1530 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1531 return ConstantFP::get(Ty->getContext(), V);
1532 }
1533
1534 if (IntrinsicID == Intrinsic::nearbyint) {
1535 APFloat V = Op->getValueAPF();
1536 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1537 return ConstantFP::get(Ty->getContext(), V);
1538 }
1539
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001540 /// We only fold functions with finite arguments. Folding NaN and inf is
1541 /// likely to be aborted with an exception anyway, and some host libms
1542 /// have known errors raising exceptions.
1543 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
Craig Topper9f008862014-04-15 04:59:12 +00001544 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001545
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001546 /// Currently APFloat versions of these functions do not exist, so we use
1547 /// the host native double versions. Float versions are not called
1548 /// directly but for all these it is true (float)(f((double)arg)) ==
1549 /// f(arg). Long double not supported yet.
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001550 double V = getValueAsDouble(Op);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001551
Benjamin Kramer061d1472014-03-05 19:41:48 +00001552 switch (IntrinsicID) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001553 default: break;
1554 case Intrinsic::fabs:
1555 return ConstantFoldFP(fabs, V, Ty);
1556 case Intrinsic::log2:
Vince Harrond5281122015-05-07 00:05:26 +00001557 return ConstantFoldFP(Log2, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001558 case Intrinsic::log:
1559 return ConstantFoldFP(log, V, Ty);
1560 case Intrinsic::log10:
1561 return ConstantFoldFP(log10, V, Ty);
1562 case Intrinsic::exp:
1563 return ConstantFoldFP(exp, V, Ty);
1564 case Intrinsic::exp2:
1565 return ConstantFoldFP(exp2, V, Ty);
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001566 case Intrinsic::sin:
1567 return ConstantFoldFP(sin, V, Ty);
1568 case Intrinsic::cos:
1569 return ConstantFoldFP(cos, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001570 }
1571
Benjamin Kramer061d1472014-03-05 19:41:48 +00001572 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001573 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001574
Daniel Dunbarca414c72009-07-26 08:34:35 +00001575 switch (Name[0]) {
Chris Lattner785f9982007-08-08 06:55:43 +00001576 case 'a':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001577 if ((Name == "acos" && TLI->has(LibFunc::acos)) ||
1578 (Name == "acosf" && TLI->has(LibFunc::acosf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001579 return ConstantFoldFP(acos, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001580 else if ((Name == "asin" && TLI->has(LibFunc::asin)) ||
1581 (Name == "asinf" && TLI->has(LibFunc::asinf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001582 return ConstantFoldFP(asin, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001583 else if ((Name == "atan" && TLI->has(LibFunc::atan)) ||
1584 (Name == "atanf" && TLI->has(LibFunc::atanf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001585 return ConstantFoldFP(atan, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001586 break;
1587 case 'c':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001588 if ((Name == "ceil" && TLI->has(LibFunc::ceil)) ||
1589 (Name == "ceilf" && TLI->has(LibFunc::ceilf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001590 return ConstantFoldFP(ceil, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001591 else if ((Name == "cos" && TLI->has(LibFunc::cos)) ||
1592 (Name == "cosf" && TLI->has(LibFunc::cosf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001593 return ConstantFoldFP(cos, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001594 else if ((Name == "cosh" && TLI->has(LibFunc::cosh)) ||
1595 (Name == "coshf" && TLI->has(LibFunc::coshf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001596 return ConstantFoldFP(cosh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001597 break;
1598 case 'e':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001599 if ((Name == "exp" && TLI->has(LibFunc::exp)) ||
1600 (Name == "expf" && TLI->has(LibFunc::expf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001601 return ConstantFoldFP(exp, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001602 if ((Name == "exp2" && TLI->has(LibFunc::exp2)) ||
1603 (Name == "exp2f" && TLI->has(LibFunc::exp2f)))
Chris Lattner713d5232011-05-22 22:22:35 +00001604 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1605 // C99 library.
1606 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001607 break;
1608 case 'f':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001609 if ((Name == "fabs" && TLI->has(LibFunc::fabs)) ||
1610 (Name == "fabsf" && TLI->has(LibFunc::fabsf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001611 return ConstantFoldFP(fabs, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001612 else if ((Name == "floor" && TLI->has(LibFunc::floor)) ||
1613 (Name == "floorf" && TLI->has(LibFunc::floorf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001614 return ConstantFoldFP(floor, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001615 break;
1616 case 'l':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001617 if ((Name == "log" && V > 0 && TLI->has(LibFunc::log)) ||
1618 (Name == "logf" && V > 0 && TLI->has(LibFunc::logf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001619 return ConstantFoldFP(log, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001620 else if ((Name == "log10" && V > 0 && TLI->has(LibFunc::log10)) ||
1621 (Name == "log10f" && V > 0 && TLI->has(LibFunc::log10f)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001622 return ConstantFoldFP(log10, V, Ty);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001623 else if (IntrinsicID == Intrinsic::sqrt &&
Owen Andersond4ebfd82013-02-06 22:43:31 +00001624 (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
Chris Lattner785f9982007-08-08 06:55:43 +00001625 if (V >= -0.0)
Chris Lattner46b5c642009-11-06 04:27:31 +00001626 return ConstantFoldFP(sqrt, V, Ty);
Sanjay Patel7b2cd9a2014-10-01 20:36:33 +00001627 else {
1628 // Unlike the sqrt definitions in C/C++, POSIX, and IEEE-754 - which
1629 // all guarantee or favor returning NaN - the square root of a
1630 // negative number is not defined for the LLVM sqrt intrinsic.
1631 // This is because the intrinsic should only be emitted in place of
1632 // libm's sqrt function when using "no-nans-fp-math".
1633 return UndefValue::get(Ty);
1634 }
Chris Lattner785f9982007-08-08 06:55:43 +00001635 }
1636 break;
1637 case 's':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001638 if ((Name == "sin" && TLI->has(LibFunc::sin)) ||
1639 (Name == "sinf" && TLI->has(LibFunc::sinf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001640 return ConstantFoldFP(sin, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001641 else if ((Name == "sinh" && TLI->has(LibFunc::sinh)) ||
1642 (Name == "sinhf" && TLI->has(LibFunc::sinhf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001643 return ConstantFoldFP(sinh, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001644 else if ((Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt)) ||
1645 (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001646 return ConstantFoldFP(sqrt, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001647 break;
1648 case 't':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001649 if ((Name == "tan" && TLI->has(LibFunc::tan)) ||
1650 (Name == "tanf" && TLI->has(LibFunc::tanf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001651 return ConstantFoldFP(tan, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001652 else if ((Name == "tanh" && TLI->has(LibFunc::tanh)) ||
1653 (Name == "tanhf" && TLI->has(LibFunc::tanhf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001654 return ConstantFoldFP(tanh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001655 break;
1656 default:
1657 break;
John Criswell970af112005-10-27 16:00:10 +00001658 }
Craig Topper9f008862014-04-15 04:59:12 +00001659 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001660 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001661
David Majnemer90a97042016-07-13 04:22:12 +00001662 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001663 switch (IntrinsicID) {
Chandler Carruth352d9b12011-01-10 09:02:58 +00001664 case Intrinsic::bswap:
Benjamin Kramer061d1472014-03-05 19:41:48 +00001665 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001666 case Intrinsic::ctpop:
Owen Andersonedb4a702009-07-24 23:12:02 +00001667 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Matt Arsenault155dda92016-03-21 15:00:35 +00001668 case Intrinsic::bitreverse:
1669 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001670 case Intrinsic::convert_from_fp16: {
Tim Northover29178a32013-01-22 09:46:31 +00001671 APFloat Val(APFloat::IEEEhalf, Op->getValue());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001672
1673 bool lost = false;
Andrea Di Biagio29059992015-05-14 18:01:48 +00001674 APFloat::opStatus status = Val.convert(
1675 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001676
1677 // Conversion is always precise.
Jeffrey Yasskin9b43f332010-12-23 00:58:24 +00001678 (void)status;
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001679 assert(status == APFloat::opOK && !lost &&
1680 "Precision lost during fp16 constfolding");
1681
Benjamin Kramer061d1472014-03-05 19:41:48 +00001682 return ConstantFP::get(Ty->getContext(), Val);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001683 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001684 default:
Craig Topper9f008862014-04-15 04:59:12 +00001685 return nullptr;
Chandler Carruth352d9b12011-01-10 09:02:58 +00001686 }
John Criswell970af112005-10-27 16:00:10 +00001687 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001688
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001689 // Support ConstantVector in case we have an Undef in the top.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001690 if (isa<ConstantVector>(Operands[0]) ||
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001691 isa<ConstantDataVector>(Operands[0])) {
David Majnemer90a97042016-07-13 04:22:12 +00001692 auto *Op = cast<Constant>(Operands[0]);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001693 switch (IntrinsicID) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001694 default: break;
1695 case Intrinsic::x86_sse_cvtss2si:
1696 case Intrinsic::x86_sse_cvtss2si64:
1697 case Intrinsic::x86_sse2_cvtsd2si:
1698 case Intrinsic::x86_sse2_cvtsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001699 if (ConstantFP *FPOp =
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001700 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1701 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1702 /*roundTowardZero=*/false, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001703 case Intrinsic::x86_sse_cvttss2si:
1704 case Intrinsic::x86_sse_cvttss2si64:
1705 case Intrinsic::x86_sse2_cvttsd2si:
1706 case Intrinsic::x86_sse2_cvttsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001707 if (ConstantFP *FPOp =
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001708 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1709 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1710 /*roundTowardZero=*/true, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001711 }
1712 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001713
Dan Gohmancf39be32010-02-17 00:54:58 +00001714 if (isa<UndefValue>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001715 if (IntrinsicID == Intrinsic::bswap)
Dan Gohmancf39be32010-02-17 00:54:58 +00001716 return Operands[0];
Craig Topper9f008862014-04-15 04:59:12 +00001717 return nullptr;
Dan Gohmancf39be32010-02-17 00:54:58 +00001718 }
1719
Craig Topper9f008862014-04-15 04:59:12 +00001720 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001721 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001722
Jay Foadf4b14a22011-07-19 13:32:40 +00001723 if (Operands.size() == 2) {
David Majnemer90a97042016-07-13 04:22:12 +00001724 if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001725 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001726 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001727 double Op1V = getValueAsDouble(Op1);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001728
David Majnemer90a97042016-07-13 04:22:12 +00001729 if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattner351534f2009-10-05 05:06:24 +00001730 if (Op2->getType() != Op1->getType())
Craig Topper9f008862014-04-15 04:59:12 +00001731 return nullptr;
Chad Rosier576c0f82011-12-01 23:16:03 +00001732
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001733 double Op2V = getValueAsDouble(Op2);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001734 if (IntrinsicID == Intrinsic::pow) {
Chad Rosier0155a632011-12-03 00:00:03 +00001735 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1736 }
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001737 if (IntrinsicID == Intrinsic::copysign) {
1738 APFloat V1 = Op1->getValueAPF();
Benjamin Kramer8f59adb2016-02-13 16:54:14 +00001739 const APFloat &V2 = Op2->getValueAPF();
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001740 V1.copySign(V2);
1741 return ConstantFP::get(Ty->getContext(), V1);
1742 }
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001743
1744 if (IntrinsicID == Intrinsic::minnum) {
1745 const APFloat &C1 = Op1->getValueAPF();
1746 const APFloat &C2 = Op2->getValueAPF();
1747 return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1748 }
1749
1750 if (IntrinsicID == Intrinsic::maxnum) {
1751 const APFloat &C1 = Op1->getValueAPF();
1752 const APFloat &C2 = Op2->getValueAPF();
1753 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1754 }
1755
Chad Rosier0155a632011-12-03 00:00:03 +00001756 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001757 return nullptr;
Erik Schnetter5e93e282015-08-27 19:56:57 +00001758 if ((Name == "pow" && TLI->has(LibFunc::pow)) ||
1759 (Name == "powf" && TLI->has(LibFunc::powf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001760 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001761 if ((Name == "fmod" && TLI->has(LibFunc::fmod)) ||
1762 (Name == "fmodf" && TLI->has(LibFunc::fmodf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001763 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001764 if ((Name == "atan2" && TLI->has(LibFunc::atan2)) ||
1765 (Name == "atan2f" && TLI->has(LibFunc::atan2f)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001766 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
David Majnemer90a97042016-07-13 04:22:12 +00001767 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001768 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1769 return ConstantFP::get(Ty->getContext(),
Owen Andersond4ebfd82013-02-06 22:43:31 +00001770 APFloat((float)std::pow((float)Op1V,
1771 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001772 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1773 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001774 APFloat((float)std::pow((float)Op1V,
Chris Lattner3b187622008-04-20 00:41:09 +00001775 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001776 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1777 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001778 APFloat((double)std::pow((double)Op1V,
1779 (int)Op2C->getZExtValue())));
John Criswell970af112005-10-27 16:00:10 +00001780 }
Craig Topper9f008862014-04-15 04:59:12 +00001781 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001782 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001783
David Majnemer90a97042016-07-13 04:22:12 +00001784 if (auto *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1785 if (auto *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001786 switch (IntrinsicID) {
Chris Lattner59d93982009-10-05 05:26:04 +00001787 default: break;
Chris Lattner698661c2010-10-14 00:05:07 +00001788 case Intrinsic::sadd_with_overflow:
1789 case Intrinsic::uadd_with_overflow:
1790 case Intrinsic::ssub_with_overflow:
1791 case Intrinsic::usub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001792 case Intrinsic::smul_with_overflow:
1793 case Intrinsic::umul_with_overflow: {
Chris Lattner698661c2010-10-14 00:05:07 +00001794 APInt Res;
1795 bool Overflow;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001796 switch (IntrinsicID) {
Craig Toppera2886c22012-02-07 05:05:23 +00001797 default: llvm_unreachable("Invalid case");
Chris Lattner698661c2010-10-14 00:05:07 +00001798 case Intrinsic::sadd_with_overflow:
1799 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1800 break;
1801 case Intrinsic::uadd_with_overflow:
1802 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1803 break;
1804 case Intrinsic::ssub_with_overflow:
1805 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1806 break;
1807 case Intrinsic::usub_with_overflow:
1808 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1809 break;
1810 case Intrinsic::smul_with_overflow:
1811 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1812 break;
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001813 case Intrinsic::umul_with_overflow:
1814 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1815 break;
Chris Lattner698661c2010-10-14 00:05:07 +00001816 }
Chris Lattner59d93982009-10-05 05:26:04 +00001817 Constant *Ops[] = {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001818 ConstantInt::get(Ty->getContext(), Res),
1819 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
Chris Lattner59d93982009-10-05 05:26:04 +00001820 };
Benjamin Kramer061d1472014-03-05 19:41:48 +00001821 return ConstantStruct::get(cast<StructType>(Ty), Ops);
Chris Lattner59d93982009-10-05 05:26:04 +00001822 }
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001823 case Intrinsic::cttz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001824 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1825 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001826 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1827 case Intrinsic::ctlz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001828 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1829 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001830 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
Chris Lattner59d93982009-10-05 05:26:04 +00001831 }
1832 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001833
Craig Topper9f008862014-04-15 04:59:12 +00001834 return nullptr;
Chris Lattner59d93982009-10-05 05:26:04 +00001835 }
Craig Topper9f008862014-04-15 04:59:12 +00001836 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001837 }
Matt Arsenault83778582014-03-05 00:02:00 +00001838
1839 if (Operands.size() != 3)
Craig Topper9f008862014-04-15 04:59:12 +00001840 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001841
David Majnemer90a97042016-07-13 04:22:12 +00001842 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1843 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1844 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001845 switch (IntrinsicID) {
Matt Arsenault83778582014-03-05 00:02:00 +00001846 default: break;
1847 case Intrinsic::fma:
1848 case Intrinsic::fmuladd: {
1849 APFloat V = Op1->getValueAPF();
1850 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1851 Op3->getValueAPF(),
1852 APFloat::rmNearestTiesToEven);
1853 if (s != APFloat::opInvalidOp)
1854 return ConstantFP::get(Ty->getContext(), V);
1855
Craig Topper9f008862014-04-15 04:59:12 +00001856 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001857 }
1858 }
1859 }
1860 }
1861 }
1862
Craig Topper9f008862014-04-15 04:59:12 +00001863 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001864}
Benjamin Kramer061d1472014-03-05 19:41:48 +00001865
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001866Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1867 VectorType *VTy, ArrayRef<Constant *> Operands,
David Majnemer7f781ab2016-07-14 00:29:50 +00001868 const DataLayout &DL,
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001869 const TargetLibraryInfo *TLI) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001870 SmallVector<Constant *, 4> Result(VTy->getNumElements());
1871 SmallVector<Constant *, 4> Lane(Operands.size());
1872 Type *Ty = VTy->getElementType();
1873
David Majnemer7f781ab2016-07-14 00:29:50 +00001874 if (IntrinsicID == Intrinsic::masked_load) {
1875 auto *SrcPtr = Operands[0];
1876 auto *Mask = Operands[2];
1877 auto *Passthru = Operands[3];
David Majnemer17a95aa2016-07-14 06:58:37 +00001878
David Majnemer7f781ab2016-07-14 00:29:50 +00001879 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, VTy, DL);
David Majnemer7f781ab2016-07-14 00:29:50 +00001880
1881 SmallVector<Constant *, 32> NewElements;
1882 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
David Majnemer17a95aa2016-07-14 06:58:37 +00001883 auto *MaskElt = Mask->getAggregateElement(I);
David Majnemer7f781ab2016-07-14 00:29:50 +00001884 if (!MaskElt)
1885 break;
David Majnemer17a95aa2016-07-14 06:58:37 +00001886 auto *PassthruElt = Passthru->getAggregateElement(I);
1887 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
1888 if (isa<UndefValue>(MaskElt)) {
1889 if (PassthruElt)
1890 NewElements.push_back(PassthruElt);
1891 else if (VecElt)
1892 NewElements.push_back(VecElt);
1893 else
1894 return nullptr;
1895 }
1896 if (MaskElt->isNullValue()) {
David Majnemer7f781ab2016-07-14 00:29:50 +00001897 if (!PassthruElt)
David Majnemer17a95aa2016-07-14 06:58:37 +00001898 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00001899 NewElements.push_back(PassthruElt);
David Majnemer17a95aa2016-07-14 06:58:37 +00001900 } else if (MaskElt->isOneValue()) {
David Majnemer7f781ab2016-07-14 00:29:50 +00001901 if (!VecElt)
David Majnemer17a95aa2016-07-14 06:58:37 +00001902 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00001903 NewElements.push_back(VecElt);
David Majnemer17a95aa2016-07-14 06:58:37 +00001904 } else {
1905 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00001906 }
1907 }
David Majnemer17a95aa2016-07-14 06:58:37 +00001908 if (NewElements.size() != VTy->getNumElements())
1909 return nullptr;
1910 return ConstantVector::get(NewElements);
David Majnemer7f781ab2016-07-14 00:29:50 +00001911 }
1912
Benjamin Kramer061d1472014-03-05 19:41:48 +00001913 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1914 // Gather a column of constants.
1915 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1916 Constant *Agg = Operands[J]->getAggregateElement(I);
1917 if (!Agg)
1918 return nullptr;
1919
1920 Lane[J] = Agg;
1921 }
1922
1923 // Use the regular scalar folding to simplify this column.
1924 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1925 if (!Folded)
1926 return nullptr;
1927 Result[I] = Folded;
1928 }
1929
1930 return ConstantVector::get(Result);
1931}
1932
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001933} // end anonymous namespace
1934
Benjamin Kramer061d1472014-03-05 19:41:48 +00001935Constant *
1936llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1937 const TargetLibraryInfo *TLI) {
1938 if (!F->hasName())
Craig Topper9f008862014-04-15 04:59:12 +00001939 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001940 StringRef Name = F->getName();
1941
1942 Type *Ty = F->getReturnType();
1943
David Majnemer90a97042016-07-13 04:22:12 +00001944 if (auto *VTy = dyn_cast<VectorType>(Ty))
David Majnemer7f781ab2016-07-14 00:29:50 +00001945 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands,
1946 F->getParent()->getDataLayout(), TLI);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001947
1948 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
1949}