blob: 85ca622a25dc83fe3532d1201efd8fe61cc26205 [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"
Eugene Zelenko1804a772016-08-25 00:45:04 +000020#include "llvm/ADT/APFloat.h"
21#include "llvm/ADT/APInt.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/DenseMap.h"
David Majnemere61e4bf2016-06-21 05:10:24 +000024#include "llvm/ADT/STLExtras.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000025#include "llvm/ADT/StringRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/ADT/SmallVector.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000027#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Analysis/ValueTracking.h"
Alp Tokerc817d6a2014-06-09 18:28:53 +000029#include "llvm/Config/config.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000030#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DerivedTypes.h"
34#include "llvm/IR/Function.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000035#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000037#include "llvm/IR/InstrTypes.h"
38#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000041#include "llvm/IR/Type.h"
42#include "llvm/IR/Value.h"
43#include "llvm/Support/Casting.h"
Torok Edwin56d06592009-07-11 20:10:48 +000044#include "llvm/Support/ErrorHandling.h"
John Criswell970af112005-10-27 16:00:10 +000045#include "llvm/Support/MathExtras.h"
Eugene Zelenko35623fb2016-03-28 17:40:08 +000046#include <cassert>
John Criswell970af112005-10-27 16:00:10 +000047#include <cerrno>
Eugene Zelenko35623fb2016-03-28 17:40:08 +000048#include <cfenv>
Jeff Cohencc08c832006-12-02 02:22:01 +000049#include <cmath>
Eugene Zelenko1804a772016-08-25 00:45:04 +000050#include <cstddef>
51#include <cstdint>
Alp Tokerc817d6a2014-06-09 18:28:53 +000052
John Criswell970af112005-10-27 16:00:10 +000053using namespace llvm;
54
Eugene Zelenko35623fb2016-03-28 17:40:08 +000055namespace {
56
Chris Lattner44d68b92007-01-31 00:51:48 +000057//===----------------------------------------------------------------------===//
58// Constant Folding internal helper functions
59//===----------------------------------------------------------------------===//
60
Matt Arsenault47a4b392016-12-02 02:26:02 +000061static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
62 Constant *C, Type *SrcEltTy,
63 unsigned NumSrcElts,
64 const DataLayout &DL) {
65 // Now that we know that the input value is a vector of integers, just shift
66 // and insert them into our result.
67 unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
68 for (unsigned i = 0; i != NumSrcElts; ++i) {
69 Constant *Element;
70 if (DL.isLittleEndian())
71 Element = C->getAggregateElement(NumSrcElts - i - 1);
72 else
73 Element = C->getAggregateElement(i);
74
75 if (Element && isa<UndefValue>(Element)) {
76 Result <<= BitShift;
77 continue;
78 }
79
80 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
81 if (!ElementCI)
82 return ConstantExpr::getBitCast(C, DestTy);
83
84 Result <<= BitShift;
85 Result |= ElementCI->getValue().zextOrSelf(Result.getBitWidth());
86 }
87
88 return nullptr;
89}
90
Matt Arsenault624e1b32016-12-07 20:56:11 +000091/// Constant fold bitcast, symbolically evaluating it with DataLayout.
Sanjay Patel0d7dee62014-10-02 15:13:22 +000092/// This always returns a non-null constant, but it may be a
Chris Lattner9d051242009-10-25 06:08:26 +000093/// ConstantExpr if unfoldable.
Eugene Zelenko35623fb2016-03-28 17:40:08 +000094Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
Nadav Rotem365af6f2011-08-24 20:18:38 +000095 // Catch the obvious splat cases.
96 if (C->isNullValue() && !DestTy->isX86_MMXTy())
97 return Constant::getNullValue(DestTy);
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +000098 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
99 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
Nadav Rotem365af6f2011-08-24 20:18:38 +0000100 return Constant::getAllOnesValue(DestTy);
101
Matt Arsenault624e1b32016-12-07 20:56:11 +0000102 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
103 // Handle a vector->scalar integer/fp cast.
104 if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) {
105 unsigned NumSrcElts = VTy->getNumElements();
106 Type *SrcEltTy = VTy->getElementType();
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000107
Matt Arsenault624e1b32016-12-07 20:56:11 +0000108 // If the vector is a vector of floating point, convert it to vector of int
109 // to simplify things.
110 if (SrcEltTy->isFloatingPointTy()) {
111 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
112 Type *SrcIVTy =
113 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
114 // Ask IR to do the conversion now that #elts line up.
115 C = ConstantExpr::getBitCast(C, SrcIVTy);
116 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000117
Matt Arsenault624e1b32016-12-07 20:56:11 +0000118 APInt Result(DL.getTypeSizeInBits(DestTy), 0);
119 if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C,
120 SrcEltTy, NumSrcElts, DL))
121 return CE;
122
123 if (isa<IntegerType>(DestTy))
124 return ConstantInt::get(DestTy, Result);
125
126 APFloat FP(DestTy->getFltSemantics(), Result);
127 return ConstantFP::get(DestTy->getContext(), FP);
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000128 }
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000129 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000130
Nadav Rotemad4a70a2011-08-20 14:02:29 +0000131 // The code below only handles casts to vectors currently.
David Majnemer90a97042016-07-13 04:22:12 +0000132 auto *DestVTy = dyn_cast<VectorType>(DestTy);
Craig Topper9f008862014-04-15 04:59:12 +0000133 if (!DestVTy)
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000134 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000135
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000136 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
137 // vector so the code below can handle it uniformly.
138 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
139 Constant *Ops = C; // don't take the address of C!
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000140 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000141 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000142
Chris Lattner9d051242009-10-25 06:08:26 +0000143 // If this is a bitcast from constant vector -> vector, fold it.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000144 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000145 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000146
Chandler Carruthef860a22013-01-02 09:10:48 +0000147 // If the element types match, IR can fold it.
Chris Lattner9d051242009-10-25 06:08:26 +0000148 unsigned NumDstElt = DestVTy->getNumElements();
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000149 unsigned NumSrcElt = C->getType()->getVectorNumElements();
Chris Lattner9d051242009-10-25 06:08:26 +0000150 if (NumDstElt == NumSrcElt)
151 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000152
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000153 Type *SrcEltTy = C->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000154 Type *DstEltTy = DestVTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000155
156 // Otherwise, we're changing the number of elements in a vector, which
Chris Lattner9d051242009-10-25 06:08:26 +0000157 // requires endianness information to do the right thing. For example,
158 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
159 // folds to (little endian):
160 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
161 // and to (big endian):
162 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000163
Chris Lattner9d051242009-10-25 06:08:26 +0000164 // First thing is first. We only want to think about integer here, so if
165 // we have something in FP form, recast it as integer.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000166 if (DstEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000167 // Fold to an vector of integers with same size as our FP type.
168 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000169 Type *DestIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000170 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
171 // Recursively handle this integer conversion, if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000172 C = FoldBitCast(C, DestIVTy, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000173
Chandler Carruthef860a22013-01-02 09:10:48 +0000174 // Finally, IR can handle this now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000175 return ConstantExpr::getBitCast(C, DestTy);
176 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000177
Chris Lattner9d051242009-10-25 06:08:26 +0000178 // Okay, we know the destination is integer, if the input is FP, convert
179 // it to integer first.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000180 if (SrcEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000181 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000182 Type *SrcIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000183 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
Chandler Carruthef860a22013-01-02 09:10:48 +0000184 // Ask IR to do the conversion now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000185 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chandler Carruthef860a22013-01-02 09:10:48 +0000186 // If IR wasn't able to fold it, bail out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000187 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
188 !isa<ConstantDataVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000189 return C;
190 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000191
Chris Lattner9d051242009-10-25 06:08:26 +0000192 // Now we know that the input and output vectors are both integer vectors
193 // of the same size, and that their #elements is not the same. Do the
194 // conversion here, which depends on whether the input or output has
195 // more elements.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000196 bool isLittleEndian = DL.isLittleEndian();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000197
Chris Lattner9d051242009-10-25 06:08:26 +0000198 SmallVector<Constant*, 32> Result;
199 if (NumDstElt < NumSrcElt) {
200 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
201 Constant *Zero = Constant::getNullValue(DstEltTy);
202 unsigned Ratio = NumSrcElt/NumDstElt;
203 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
204 unsigned SrcElt = 0;
205 for (unsigned i = 0; i != NumDstElt; ++i) {
206 // Build each element of the result.
207 Constant *Elt = Zero;
208 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
209 for (unsigned j = 0; j != Ratio; ++j) {
David Majnemere4218cf2016-07-29 04:06:09 +0000210 Constant *Src = C->getAggregateElement(SrcElt++);
211 if (Src && isa<UndefValue>(Src))
David Majnemer718da3d2016-07-29 18:48:27 +0000212 Src = Constant::getNullValue(C->getType()->getVectorElementType());
David Majnemere4218cf2016-07-29 04:06:09 +0000213 else
214 Src = dyn_cast_or_null<ConstantInt>(Src);
Chris Lattner9d051242009-10-25 06:08:26 +0000215 if (!Src) // Reject constantexpr elements.
216 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000217
Chris Lattner9d051242009-10-25 06:08:26 +0000218 // Zero extend the element to the right size.
219 Src = ConstantExpr::getZExt(Src, Elt->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000220
Chris Lattner9d051242009-10-25 06:08:26 +0000221 // Shift it to the right place, depending on endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000222 Src = ConstantExpr::getShl(Src,
Chris Lattner9d051242009-10-25 06:08:26 +0000223 ConstantInt::get(Src->getType(), ShiftAmt));
224 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000225
Chris Lattner9d051242009-10-25 06:08:26 +0000226 // Mix it in.
227 Elt = ConstantExpr::getOr(Elt, Src);
228 }
229 Result.push_back(Elt);
230 }
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000231 return ConstantVector::get(Result);
232 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000233
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000234 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
235 unsigned Ratio = NumDstElt/NumSrcElt;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000236 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000237
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000238 // Loop over each source value, expanding into multiple results.
239 for (unsigned i = 0; i != NumSrcElt; ++i) {
Andrea Di Biagio7277afe2016-09-13 14:50:47 +0000240 auto *Element = C->getAggregateElement(i);
241
242 if (!Element) // Reject constantexpr elements.
243 return ConstantExpr::getBitCast(C, DestTy);
244
245 if (isa<UndefValue>(Element)) {
246 // Correctly Propagate undef values.
247 Result.append(Ratio, UndefValue::get(DstEltTy));
248 continue;
249 }
250
251 auto *Src = dyn_cast<ConstantInt>(Element);
252 if (!Src)
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000253 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000254
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000255 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
256 for (unsigned j = 0; j != Ratio; ++j) {
257 // Shift the piece of the value into the right place, depending on
258 // endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000259 Constant *Elt = ConstantExpr::getLShr(Src,
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000260 ConstantInt::get(Src->getType(), ShiftAmt));
261 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000262
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +0000263 // Truncate the element to an integer with the same pointer size and
264 // convert the element back to a pointer using a inttoptr.
265 if (DstEltTy->isPointerTy()) {
266 IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
267 Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
268 Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
269 continue;
270 }
271
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000272 // Truncate and remember this piece.
273 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner9d051242009-10-25 06:08:26 +0000274 }
275 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000276
Chris Lattner69229312011-02-15 00:14:00 +0000277 return ConstantVector::get(Result);
Chris Lattner9d051242009-10-25 06:08:26 +0000278}
279
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000280} // end anonymous namespace
281
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000282/// If this constant is a constant offset from a global, return the global and
283/// the constant. Because of constantexprs, this function is recursive.
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000284bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
285 APInt &Offset, const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000286 // Trivial case, constant is the global.
287 if ((GV = dyn_cast<GlobalValue>(C))) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000288 unsigned BitWidth = DL.getPointerTypeSizeInBits(GV->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000289 Offset = APInt(BitWidth, 0);
Chris Lattner44d68b92007-01-31 00:51:48 +0000290 return true;
291 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000292
Chris Lattner44d68b92007-01-31 00:51:48 +0000293 // Otherwise, if this isn't a constant expr, bail out.
David Majnemer90a97042016-07-13 04:22:12 +0000294 auto *CE = dyn_cast<ConstantExpr>(C);
Chris Lattner44d68b92007-01-31 00:51:48 +0000295 if (!CE) return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000296
Chris Lattner44d68b92007-01-31 00:51:48 +0000297 // Look through ptr->int and ptr->ptr casts.
298 if (CE->getOpcode() == Instruction::PtrToInt ||
Matt Arsenault95365ca2015-07-27 18:31:03 +0000299 CE->getOpcode() == Instruction::BitCast)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000300 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000301
302 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
David Majnemer90a97042016-07-13 04:22:12 +0000303 auto *GEP = dyn_cast<GEPOperator>(CE);
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000304 if (!GEP)
305 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000306
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000307 unsigned BitWidth = DL.getPointerTypeSizeInBits(GEP->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000308 APInt TmpOffset(BitWidth, 0);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000309
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000310 // If the base isn't a global+constant, we aren't either.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000311 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000312 return false;
313
314 // Otherwise, add any offset that our operands provide.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000315 if (!GEP->accumulateConstantOffset(DL, TmpOffset))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000316 return false;
317
318 Offset = TmpOffset;
319 return true;
Chris Lattner44d68b92007-01-31 00:51:48 +0000320}
321
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000322namespace {
323
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000324/// Recursive helper to read bits out of global. C is the constant being copied
325/// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
326/// results into and BytesLeft is the number of bytes left in
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000327/// the CurPtr buffer. DL is the DataLayout.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000328bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
329 unsigned BytesLeft, const DataLayout &DL) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000330 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
Chris Lattnered00b802009-10-23 06:23:49 +0000331 "Out of range access");
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000332
Chris Lattner3db7bd22009-10-24 05:27:19 +0000333 // If this element is zero or undefined, we can just return since *CurPtr is
334 // zero initialized.
Chris Lattnered00b802009-10-23 06:23:49 +0000335 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
336 return true;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000337
David Majnemer90a97042016-07-13 04:22:12 +0000338 if (auto *CI = dyn_cast<ConstantInt>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000339 if (CI->getBitWidth() > 64 ||
340 (CI->getBitWidth() & 7) != 0)
341 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000342
Chris Lattnered00b802009-10-23 06:23:49 +0000343 uint64_t Val = CI->getZExtValue();
344 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000345
Chris Lattnered00b802009-10-23 06:23:49 +0000346 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000347 int n = ByteOffset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000348 if (!DL.isLittleEndian())
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000349 n = IntBytes - n - 1;
350 CurPtr[i] = (unsigned char)(Val >> (n * 8));
Chris Lattnered00b802009-10-23 06:23:49 +0000351 ++ByteOffset;
352 }
353 return true;
354 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000355
David Majnemer90a97042016-07-13 04:22:12 +0000356 if (auto *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000357 if (CFP->getType()->isDoubleTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000358 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
359 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000360 }
361 if (CFP->getType()->isFloatTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000362 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
363 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000364 }
Owen Andersond4ebfd82013-02-06 22:43:31 +0000365 if (CFP->getType()->isHalfTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000366 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
367 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Owen Andersond4ebfd82013-02-06 22:43:31 +0000368 }
Chris Lattner3db7bd22009-10-24 05:27:19 +0000369 return false;
Chris Lattnered00b802009-10-23 06:23:49 +0000370 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000371
David Majnemer90a97042016-07-13 04:22:12 +0000372 if (auto *CS = dyn_cast<ConstantStruct>(C)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000373 const StructLayout *SL = DL.getStructLayout(CS->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000374 unsigned Index = SL->getElementContainingOffset(ByteOffset);
375 uint64_t CurEltOffset = SL->getElementOffset(Index);
376 ByteOffset -= CurEltOffset;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000377
Eugene Zelenko1804a772016-08-25 00:45:04 +0000378 while (true) {
Chris Lattnered00b802009-10-23 06:23:49 +0000379 // If the element access is to the element itself and not to tail padding,
380 // read the bytes from the element.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000381 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000382
383 if (ByteOffset < EltSize &&
384 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000385 BytesLeft, DL))
Chris Lattnered00b802009-10-23 06:23:49 +0000386 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000387
Chris Lattnered00b802009-10-23 06:23:49 +0000388 ++Index;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000389
Chris Lattnered00b802009-10-23 06:23:49 +0000390 // Check to see if we read from the last struct element, if so we're done.
391 if (Index == CS->getType()->getNumElements())
392 return true;
393
394 // If we read all of the bytes we needed from this element we're done.
395 uint64_t NextEltOffset = SL->getElementOffset(Index);
396
Matt Arsenault8c789092013-08-12 23:15:58 +0000397 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
Chris Lattnered00b802009-10-23 06:23:49 +0000398 return true;
399
400 // Move to the next element of the struct.
Matt Arsenault8c789092013-08-12 23:15:58 +0000401 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
402 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
Chris Lattnered00b802009-10-23 06:23:49 +0000403 ByteOffset = 0;
404 CurEltOffset = NextEltOffset;
405 }
406 // not reached.
407 }
408
Chris Lattner67058832012-01-25 06:48:06 +0000409 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
410 isa<ConstantDataSequential>(C)) {
Matt Arsenault8c789092013-08-12 23:15:58 +0000411 Type *EltTy = C->getType()->getSequentialElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000412 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
Chris Lattnered00b802009-10-23 06:23:49 +0000413 uint64_t Index = ByteOffset / EltSize;
414 uint64_t Offset = ByteOffset - Index * EltSize;
Chris Lattner67058832012-01-25 06:48:06 +0000415 uint64_t NumElts;
David Majnemer90a97042016-07-13 04:22:12 +0000416 if (auto *AT = dyn_cast<ArrayType>(C->getType()))
Chris Lattner67058832012-01-25 06:48:06 +0000417 NumElts = AT->getNumElements();
418 else
Matt Arsenault8c789092013-08-12 23:15:58 +0000419 NumElts = C->getType()->getVectorNumElements();
Duncan Sands0b875a02012-07-25 09:14:54 +0000420
Chris Lattner67058832012-01-25 06:48:06 +0000421 for (; Index != NumElts; ++Index) {
422 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000423 BytesLeft, DL))
Chris Lattner67058832012-01-25 06:48:06 +0000424 return false;
Duncan Sands0b875a02012-07-25 09:14:54 +0000425
426 uint64_t BytesWritten = EltSize - Offset;
427 assert(BytesWritten <= EltSize && "Not indexing into this element?");
428 if (BytesWritten >= BytesLeft)
Chris Lattner67058832012-01-25 06:48:06 +0000429 return true;
Duncan Sands0b875a02012-07-25 09:14:54 +0000430
Chris Lattner67058832012-01-25 06:48:06 +0000431 Offset = 0;
Duncan Sands0b875a02012-07-25 09:14:54 +0000432 BytesLeft -= BytesWritten;
433 CurPtr += BytesWritten;
Chris Lattner67058832012-01-25 06:48:06 +0000434 }
435 return true;
436 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000437
David Majnemer90a97042016-07-13 04:22:12 +0000438 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Anders Carlssonecf8e152011-02-06 20:22:49 +0000439 if (CE->getOpcode() == Instruction::IntToPtr &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000440 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000441 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000442 BytesLeft, DL);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000443 }
Anders Carlssond21b06a2011-02-06 20:11:56 +0000444 }
445
Chris Lattnered00b802009-10-23 06:23:49 +0000446 // Otherwise, unknown initializer type.
447 return false;
448}
449
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000450Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
451 const DataLayout &DL) {
David Majnemer90a97042016-07-13 04:22:12 +0000452 auto *PTy = cast<PointerType>(C->getType());
453 auto *IntType = dyn_cast<IntegerType>(LoadTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000454
Chris Lattnered00b802009-10-23 06:23:49 +0000455 // If this isn't an integer load we can't fold it directly.
456 if (!IntType) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000457 unsigned AS = PTy->getAddressSpace();
458
Chris Lattnered00b802009-10-23 06:23:49 +0000459 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattnerccf1e842009-10-23 06:57:37 +0000460 // and then bitcast the result. This can be useful for union cases. Note
461 // that address spaces don't matter here since we're not going to result in
462 // an actual new load.
Chris Lattner229907c2011-07-18 04:54:35 +0000463 Type *MapTy;
Owen Andersond4ebfd82013-02-06 22:43:31 +0000464 if (LoadTy->isHalfTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000465 MapTy = Type::getInt16Ty(C->getContext());
Owen Andersond4ebfd82013-02-06 22:43:31 +0000466 else if (LoadTy->isFloatTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000467 MapTy = Type::getInt32Ty(C->getContext());
Chris Lattnerccf1e842009-10-23 06:57:37 +0000468 else if (LoadTy->isDoubleTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000469 MapTy = Type::getInt64Ty(C->getContext());
Duncan Sands19d0b472010-02-16 11:11:14 +0000470 else if (LoadTy->isVectorTy()) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000471 MapTy = PointerType::getIntNTy(C->getContext(),
472 DL.getTypeAllocSizeInBits(LoadTy));
Chris Lattnerccf1e842009-10-23 06:57:37 +0000473 } else
Craig Topper9f008862014-04-15 04:59:12 +0000474 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000475
Eduard Burtescu14239212016-01-22 01:17:26 +0000476 C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
477 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000478 return FoldBitCast(Res, LoadTy, DL);
Craig Topper9f008862014-04-15 04:59:12 +0000479 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000480 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000481
Chris Lattnered00b802009-10-23 06:23:49 +0000482 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Matt Arsenault8c789092013-08-12 23:15:58 +0000483 if (BytesLoaded > 32 || BytesLoaded == 0)
Craig Topper9f008862014-04-15 04:59:12 +0000484 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000485
Chris Lattnered00b802009-10-23 06:23:49 +0000486 GlobalValue *GVal;
David Majnemerf89660a2016-07-13 23:33:07 +0000487 APInt OffsetAI;
488 if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000489 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000490
David Majnemer90a97042016-07-13 04:22:12 +0000491 auto *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattner3db7bd22009-10-24 05:27:19 +0000492 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnered00b802009-10-23 06:23:49 +0000493 !GV->getInitializer()->getType()->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000494 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000495
David Majnemerf89660a2016-07-13 23:33:07 +0000496 int64_t Offset = OffsetAI.getSExtValue();
497 int64_t InitializerSize = DL.getTypeAllocSize(GV->getInitializer()->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000498
Chris Lattnered00b802009-10-23 06:23:49 +0000499 // If we're not accessing anything in this constant, the result is undefined.
David Majnemerf89660a2016-07-13 23:33:07 +0000500 if (Offset + BytesLoaded <= 0)
501 return UndefValue::get(IntType);
502
503 // If we're not accessing anything in this constant, the result is undefined.
504 if (Offset >= InitializerSize)
Chris Lattnered00b802009-10-23 06:23:49 +0000505 return UndefValue::get(IntType);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000506
Chris Lattner59f94c02009-10-23 06:50:36 +0000507 unsigned char RawBytes[32] = {0};
David Majnemerf89660a2016-07-13 23:33:07 +0000508 unsigned char *CurPtr = RawBytes;
509 unsigned BytesLeft = BytesLoaded;
510
511 // If we're loading off the beginning of the global, some bytes may be valid.
512 if (Offset < 0) {
513 CurPtr += -Offset;
514 BytesLeft += Offset;
515 Offset = 0;
516 }
517
518 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000519 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000520
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000521 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000522 if (DL.isLittleEndian()) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000523 ResultVal = RawBytes[BytesLoaded - 1];
524 for (unsigned i = 1; i != BytesLoaded; ++i) {
525 ResultVal <<= 8;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000526 ResultVal |= RawBytes[BytesLoaded - 1 - i];
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000527 }
528 } else {
529 ResultVal = RawBytes[0];
530 for (unsigned i = 1; i != BytesLoaded; ++i) {
531 ResultVal <<= 8;
532 ResultVal |= RawBytes[i];
533 }
Chris Lattner59f94c02009-10-23 06:50:36 +0000534 }
Chris Lattnered00b802009-10-23 06:23:49 +0000535
Chris Lattner59f94c02009-10-23 06:50:36 +0000536 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnered00b802009-10-23 06:23:49 +0000537}
538
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000539Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE, Type *DestTy,
540 const DataLayout &DL) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000541 auto *SrcPtr = CE->getOperand(0);
542 auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
543 if (!SrcPtrTy)
Chandler Carrutha0e56952014-05-15 09:56:28 +0000544 return nullptr;
Eduard Burtescu14239212016-01-22 01:17:26 +0000545 Type *SrcTy = SrcPtrTy->getPointerElementType();
Chandler Carrutha0e56952014-05-15 09:56:28 +0000546
Eduard Burtescu14239212016-01-22 01:17:26 +0000547 Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
Chandler Carrutha0e56952014-05-15 09:56:28 +0000548 if (!C)
549 return nullptr;
550
551 do {
552 Type *SrcTy = C->getType();
553
554 // If the type sizes are the same and a cast is legal, just directly
555 // cast the constant.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000556 if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
Chandler Carrutha0e56952014-05-15 09:56:28 +0000557 Instruction::CastOps Cast = Instruction::BitCast;
558 // If we are going from a pointer to int or vice versa, we spell the cast
559 // differently.
560 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
561 Cast = Instruction::IntToPtr;
562 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
563 Cast = Instruction::PtrToInt;
564
565 if (CastInst::castIsValid(Cast, C, DestTy))
566 return ConstantExpr::getCast(Cast, C, DestTy);
567 }
568
569 // If this isn't an aggregate type, there is nothing we can do to drill down
570 // and find a bitcastable constant.
571 if (!SrcTy->isAggregateType())
572 return nullptr;
573
574 // We're simulating a load through a pointer that was bitcast to point to
575 // a different type, so we can try to walk down through the initial
576 // elements of an aggregate to see if some part of th e aggregate is
577 // castable to implement the "load" semantic model.
578 C = C->getAggregateElement(0u);
579 } while (C);
580
581 return nullptr;
582}
583
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000584} // end anonymous namespace
585
Eduard Burtescu14239212016-01-22 01:17:26 +0000586Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000587 const DataLayout &DL) {
Chris Lattner1664a4f2009-10-22 06:25:11 +0000588 // First, try the easy cases:
David Majnemer90a97042016-07-13 04:22:12 +0000589 if (auto *GV = dyn_cast<GlobalVariable>(C))
Chris Lattner1664a4f2009-10-22 06:25:11 +0000590 if (GV->isConstant() && GV->hasDefinitiveInitializer())
591 return GV->getInitializer();
592
David Majnemered9abe12015-07-22 22:29:30 +0000593 if (auto *GA = dyn_cast<GlobalAlias>(C))
Sanjoy Das5ce32722016-04-08 00:48:30 +0000594 if (GA->getAliasee() && !GA->isInterposable())
Eduard Burtescu14239212016-01-22 01:17:26 +0000595 return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
David Majnemered9abe12015-07-22 22:29:30 +0000596
Chris Lattnercf7e8942009-10-22 06:44:07 +0000597 // If the loaded value isn't a constant expr, we can't handle it.
David Majnemer90a97042016-07-13 04:22:12 +0000598 auto *CE = dyn_cast<ConstantExpr>(C);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000599 if (!CE)
Craig Topper9f008862014-04-15 04:59:12 +0000600 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000601
Chris Lattnercf7e8942009-10-22 06:44:07 +0000602 if (CE->getOpcode() == Instruction::GetElementPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000603 if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000604 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000605 if (Constant *V =
Chris Lattnercf7e8942009-10-22 06:44:07 +0000606 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
607 return V;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000608 }
609 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000610 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000611
Chandler Carrutha0e56952014-05-15 09:56:28 +0000612 if (CE->getOpcode() == Instruction::BitCast)
Eduard Burtescu14239212016-01-22 01:17:26 +0000613 if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, Ty, DL))
Chandler Carrutha0e56952014-05-15 09:56:28 +0000614 return LoadedC;
615
Chris Lattnercf7e8942009-10-22 06:44:07 +0000616 // Instead of loading constant c string, use corresponding integer value
617 // directly if string length is small enough.
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000618 StringRef Str;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000619 if (getConstantStringInfo(CE, Str) && !Str.empty()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000620 size_t StrLen = Str.size();
Chris Lattnered00b802009-10-23 06:23:49 +0000621 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000622 // Replace load with immediate integer if the result is an integer or fp
623 // value.
624 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
Chandler Carruth57041d82010-07-12 06:47:05 +0000625 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
Chris Lattnered00b802009-10-23 06:23:49 +0000626 APInt StrVal(NumBits, 0);
627 APInt SingleChar(NumBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000628 if (DL.isLittleEndian()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000629 for (unsigned char C : reverse(Str.bytes())) {
630 SingleChar = static_cast<uint64_t>(C);
Chris Lattner51d2f702009-10-22 06:38:35 +0000631 StrVal = (StrVal << 8) | SingleChar;
632 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000633 } else {
David Majnemere61e4bf2016-06-21 05:10:24 +0000634 for (unsigned char C : Str.bytes()) {
635 SingleChar = static_cast<uint64_t>(C);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000636 StrVal = (StrVal << 8) | SingleChar;
637 }
638 // Append NULL at the end.
639 SingleChar = 0;
640 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner51d2f702009-10-22 06:38:35 +0000641 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000642
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000643 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
644 if (Ty->isFloatingPointTy())
645 Res = ConstantExpr::getBitCast(Res, Ty);
646 return Res;
Chris Lattner51d2f702009-10-22 06:38:35 +0000647 }
Chris Lattner1664a4f2009-10-22 06:25:11 +0000648 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000649
Chris Lattnercf7e8942009-10-22 06:44:07 +0000650 // If this load comes from anywhere in a constant global, and if the global
651 // is all undef or zero, we know what it loads.
David Majnemer90a97042016-07-13 04:22:12 +0000652 if (auto *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000653 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000654 if (GV->getInitializer()->isNullValue())
Eduard Burtescu14239212016-01-22 01:17:26 +0000655 return Constant::getNullValue(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000656 if (isa<UndefValue>(GV->getInitializer()))
Eduard Burtescu14239212016-01-22 01:17:26 +0000657 return UndefValue::get(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000658 }
659 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000660
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000661 // Try hard to fold loads from bitcasted strange and non-type-safe things.
Eduard Burtescu14239212016-01-22 01:17:26 +0000662 return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
Chris Lattner1664a4f2009-10-22 06:25:11 +0000663}
664
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000665namespace {
666
667Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) {
Craig Topper9f008862014-04-15 04:59:12 +0000668 if (LI->isVolatile()) return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000669
David Majnemer90a97042016-07-13 04:22:12 +0000670 if (auto *C = dyn_cast<Constant>(LI->getOperand(0)))
Eduard Burtescu14239212016-01-22 01:17:26 +0000671 return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000672
Craig Topper9f008862014-04-15 04:59:12 +0000673 return nullptr;
Chris Lattner1664a4f2009-10-22 06:25:11 +0000674}
Chris Lattner44d68b92007-01-31 00:51:48 +0000675
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000676/// One of Op0/Op1 is a constant expression.
Nick Lewyckye88d3882008-12-15 01:35:36 +0000677/// Attempt to symbolically evaluate the result of a binary operator merging
Nick Lewycky06417742013-02-14 03:23:37 +0000678/// these together. If target data info is available, it is provided as DL,
679/// otherwise DL is null.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000680Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
681 const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000682 // SROA
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000683
Chris Lattner44d68b92007-01-31 00:51:48 +0000684 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
685 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
686 // bits.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000687
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000688 if (Opc == Instruction::And) {
689 unsigned BitWidth = DL.getTypeSizeInBits(Op0->getType()->getScalarType());
Nick Lewycky06417742013-02-14 03:23:37 +0000690 APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
691 APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
Jay Foada0653a32014-05-14 21:14:37 +0000692 computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
693 computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
Nick Lewycky06417742013-02-14 03:23:37 +0000694 if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
695 // All the bits of Op0 that the 'and' could be masking are already zero.
696 return Op0;
697 }
698 if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
699 // All the bits of Op1 that the 'and' could be masking are already zero.
700 return Op1;
701 }
702
703 APInt KnownZero = KnownZero0 | KnownZero1;
704 APInt KnownOne = KnownOne0 & KnownOne1;
705 if ((KnownZero | KnownOne).isAllOnesValue()) {
706 return ConstantInt::get(Op0->getType(), KnownOne);
707 }
708 }
709
Chris Lattner44d68b92007-01-31 00:51:48 +0000710 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
711 // constant. This happens frequently when iterating over a global array.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000712 if (Opc == Instruction::Sub) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000713 GlobalValue *GV1, *GV2;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000714 APInt Offs1, Offs2;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000715
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000716 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
717 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
718 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
Matt Arsenaultbed5bf22013-09-12 01:07:58 +0000719
Chris Lattner44d68b92007-01-31 00:51:48 +0000720 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Benjamin Kramera5a9ec52013-02-05 19:04:36 +0000721 // PtrToInt may change the bitwidth so we have convert to the right size
722 // first.
723 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
724 Offs2.zextOrTrunc(OpSize));
Chris Lattner44d68b92007-01-31 00:51:48 +0000725 }
726 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000727
Craig Topper9f008862014-04-15 04:59:12 +0000728 return nullptr;
Chris Lattner44d68b92007-01-31 00:51:48 +0000729}
730
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000731/// If array indices are not pointer-sized integers, explicitly cast them so
732/// that they aren't implicitly casted by the getelementptr.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000733Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
Peter Collingbourned93620b2016-11-10 22:34:55 +0000734 Type *ResultTy, Optional<unsigned> InRangeIndex,
735 const DataLayout &DL, const TargetLibraryInfo *TLI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000736 Type *IntPtrTy = DL.getIntPtrType(ResultTy);
Keno Fischerdc091192016-12-08 17:22:35 +0000737 Type *IntPtrScalarTy = IntPtrTy->getScalarType();
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000738
739 bool Any = false;
740 SmallVector<Constant*, 32> NewIdxs;
Jay Foadf4b14a22011-07-19 13:32:40 +0000741 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000742 if ((i == 1 ||
Keno Fischerdc091192016-12-08 17:22:35 +0000743 !isa<StructType>(GetElementPtrInst::getIndexedType(
744 SrcElemTy, Ops.slice(1, i - 1)))) &&
Michael Kupersteindd92c782016-12-21 17:34:21 +0000745 Ops[i]->getType()->getScalarType() != IntPtrScalarTy) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000746 Any = true;
Michael Kupersteindd92c782016-12-21 17:34:21 +0000747 Type *NewType = Ops[i]->getType()->isVectorTy()
748 ? IntPtrTy
749 : IntPtrTy->getScalarType();
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000750 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
751 true,
Michael Kupersteindd92c782016-12-21 17:34:21 +0000752 NewType,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000753 true),
Michael Kupersteindd92c782016-12-21 17:34:21 +0000754 Ops[i], NewType));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000755 } else
756 NewIdxs.push_back(Ops[i]);
757 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000758
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000759 if (!Any)
Craig Topper9f008862014-04-15 04:59:12 +0000760 return nullptr;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000761
Peter Collingbourned93620b2016-11-10 22:34:55 +0000762 Constant *C = ConstantExpr::getGetElementPtr(
763 SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex);
David Majnemerd536f232016-07-29 03:27:26 +0000764 if (Constant *Folded = ConstantFoldConstant(C, DL, TLI))
765 C = Folded;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000766
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000767 return C;
768}
769
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000770/// Strip the pointer casts, but preserve the address space information.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000771Constant* StripPtrCastKeepAS(Constant* Ptr, Type *&ElemTy) {
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000772 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
David Majnemer90a97042016-07-13 04:22:12 +0000773 auto *OldPtrTy = cast<PointerType>(Ptr->getType());
Rafael Espindola78598d92014-06-04 19:01:48 +0000774 Ptr = Ptr->stripPointerCasts();
David Majnemer90a97042016-07-13 04:22:12 +0000775 auto *NewPtrTy = cast<PointerType>(Ptr->getType());
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000776
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000777 ElemTy = NewPtrTy->getPointerElementType();
778
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000779 // Preserve the address space number of the pointer.
780 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000781 NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000782 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000783 }
784 return Ptr;
785}
786
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000787/// If we can symbolically evaluate the GEP constant expression, do so.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000788Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
789 ArrayRef<Constant *> Ops,
790 const DataLayout &DL,
791 const TargetLibraryInfo *TLI) {
Peter Collingbourned93620b2016-11-10 22:34:55 +0000792 const GEPOperator *InnermostGEP = GEP;
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000793 bool InBounds = GEP->isInBounds();
Peter Collingbourned93620b2016-11-10 22:34:55 +0000794
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000795 Type *SrcElemTy = GEP->getSourceElementType();
796 Type *ResElemTy = GEP->getResultElementType();
797 Type *ResTy = GEP->getType();
798 if (!SrcElemTy->isSized())
799 return nullptr;
800
Peter Collingbourned93620b2016-11-10 22:34:55 +0000801 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy,
802 GEP->getInRangeIndex(), DL, TLI))
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000803 return C;
804
Chris Lattner44d68b92007-01-31 00:51:48 +0000805 Constant *Ptr = Ops[0];
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000806 if (!Ptr->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +0000807 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000808
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000809 Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
Chris Lattnerf4b42f52008-05-08 04:54:43 +0000810
811 // If this is a constant expr gep that is effectively computing an
812 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
Jay Foadf4b14a22011-07-19 13:32:40 +0000813 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Chris Lattner5858e092011-01-06 06:19:46 +0000814 if (!isa<ConstantInt>(Ops[i])) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000815
Chris Lattner5858e092011-01-06 06:19:46 +0000816 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
817 // "inttoptr (sub (ptrtoint Ptr), V)"
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000818 if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
David Majnemer90a97042016-07-13 04:22:12 +0000819 auto *CE = dyn_cast<ConstantExpr>(Ops[1]);
Craig Topper9f008862014-04-15 04:59:12 +0000820 assert((!CE || CE->getType() == IntPtrTy) &&
Chris Lattner171608e2011-01-06 22:24:29 +0000821 "CastGEPIndices didn't canonicalize index types!");
Chris Lattner5858e092011-01-06 06:19:46 +0000822 if (CE && CE->getOpcode() == Instruction::Sub &&
Chris Lattner171608e2011-01-06 22:24:29 +0000823 CE->getOperand(0)->isNullValue()) {
Chris Lattner5858e092011-01-06 06:19:46 +0000824 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
825 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000826 Res = ConstantExpr::getIntToPtr(Res, ResTy);
David Majnemerd536f232016-07-29 03:27:26 +0000827 if (auto *FoldedRes = ConstantFoldConstant(Res, DL, TLI))
828 Res = FoldedRes;
Chris Lattner5858e092011-01-06 06:19:46 +0000829 return Res;
830 }
831 }
Craig Topper9f008862014-04-15 04:59:12 +0000832 return nullptr;
Chris Lattner5858e092011-01-06 06:19:46 +0000833 }
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000834
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000835 unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
Jay Foadbf904772011-07-19 14:01:37 +0000836 APInt Offset =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000837 APInt(BitWidth,
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000838 DL.getIndexedOffsetInType(
839 SrcElemTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000840 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000841 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000842
843 // If this is a GEP of a GEP, fold it all into a single GEP.
David Majnemer90a97042016-07-13 04:22:12 +0000844 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
Peter Collingbourned93620b2016-11-10 22:34:55 +0000845 InnermostGEP = GEP;
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000846 InBounds &= GEP->isInBounds();
Peter Collingbourned93620b2016-11-10 22:34:55 +0000847
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000848 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
Duncan Sands8c355062010-03-12 17:55:20 +0000849
850 // Do not try the incorporate the sub-GEP if some index is not a number.
851 bool AllConstantInt = true;
David Majnemer90a97042016-07-13 04:22:12 +0000852 for (Value *NestedOp : NestedOps)
853 if (!isa<ConstantInt>(NestedOp)) {
Duncan Sands8c355062010-03-12 17:55:20 +0000854 AllConstantInt = false;
855 break;
856 }
857 if (!AllConstantInt)
858 break;
859
Dan Gohman474e488c2010-03-10 19:31:51 +0000860 Ptr = cast<Constant>(GEP->getOperand(0));
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000861 SrcElemTy = GEP->getSourceElementType();
862 Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000863 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000864 }
865
Dan Gohman81ce8422009-08-19 18:18:36 +0000866 // If the base value for this address is a literal integer value, fold the
867 // getelementptr to the resulting integer value casted to the pointer type.
Dan Gohmana5ca5782010-03-18 19:34:33 +0000868 APInt BasePtr(BitWidth, 0);
David Majnemer90a97042016-07-13 04:22:12 +0000869 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000870 if (CE->getOpcode() == Instruction::IntToPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000871 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
Jay Foad583abbc2010-12-07 08:25:19 +0000872 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000873 }
874 }
875
Sanjoy Das6fa08aa2016-08-05 19:23:29 +0000876 auto *PTy = cast<PointerType>(Ptr->getType());
877 if ((Ptr->isNullValue() || BasePtr != 0) &&
878 !DL.isNonIntegralPointerType(PTy)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000879 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000880 return ConstantExpr::getIntToPtr(C, ResTy);
Dan Gohman81ce8422009-08-19 18:18:36 +0000881 }
882
883 // Otherwise form a regular getelementptr. Recompute the indices so that
884 // we eliminate over-indexing of the notional static type array bounds.
885 // This makes it easy to determine if the getelementptr is "inbounds".
886 // Also, this helps GlobalOpt do SROA on GlobalVariables.
Sanjoy Das6fa08aa2016-08-05 19:23:29 +0000887 Type *Ty = PTy;
Matt Arsenault7a960a82013-08-20 21:20:04 +0000888 SmallVector<Constant *, 32> NewIdxs;
889
Dan Gohmanc59ba422009-08-19 22:46:59 +0000890 do {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000891 if (!Ty->isStructTy()) {
892 if (Ty->isPointerTy()) {
Chris Lattner77c36d62009-12-03 01:05:45 +0000893 // The only pointer indexing we'll do is on the first index of the GEP.
894 if (!NewIdxs.empty())
895 break;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000896
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000897 Ty = SrcElemTy;
898
Chris Lattner77c36d62009-12-03 01:05:45 +0000899 // Only handle pointers to sized types, not pointers to functions.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000900 if (!Ty->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000901 return nullptr;
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000902 } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) {
903 Ty = ATy->getElementType();
904 } else {
905 // We've reached some non-indexable type.
906 break;
Chris Lattner77c36d62009-12-03 01:05:45 +0000907 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000908
Dan Gohman81ce8422009-08-19 18:18:36 +0000909 // Determine which element of the array the offset points into.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000910 APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
David Majnemer1b3db332016-07-13 05:16:16 +0000911 if (ElemSize == 0) {
Chris Lattner6ce03802010-11-21 08:39:01 +0000912 // The element size is 0. This may be [0 x Ty]*, so just use a zero
Duncan Sands1f86be92010-11-21 12:43:13 +0000913 // index for this level and proceed to the next level to see if it can
914 // accommodate the offset.
Chris Lattner6ce03802010-11-21 08:39:01 +0000915 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
David Majnemer1b3db332016-07-13 05:16:16 +0000916 } else {
Chris Lattner6ce03802010-11-21 08:39:01 +0000917 // The element size is non-zero divide the offset by the element
918 // size (rounding down), to compute the index at this level.
David Majnemer4cff2f82016-07-13 15:53:46 +0000919 bool Overflow;
920 APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow);
921 if (Overflow)
922 break;
Chris Lattner6ce03802010-11-21 08:39:01 +0000923 Offset -= NewIdx * ElemSize;
924 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
925 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000926 } else {
David Majnemer90a97042016-07-13 04:22:12 +0000927 auto *STy = cast<StructType>(Ty);
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000928 // If we end up with an offset that isn't valid for this struct type, we
929 // can't re-form this GEP in a regular form, so bail out. The pointer
930 // operand likely went through casts that are necessary to make the GEP
931 // sensible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000932 const StructLayout &SL = *DL.getStructLayout(STy);
David Majnemer1b3db332016-07-13 05:16:16 +0000933 if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes()))
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000934 break;
935
936 // Determine which field of the struct the offset points into. The
937 // getZExtValue is fine as we've already ensured that the offset is
938 // within the range representable by the StructLayout API.
Dan Gohman23e62c52009-08-21 16:52:54 +0000939 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Chris Lattner46b5c642009-11-06 04:27:31 +0000940 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
941 ElIdx));
Dan Gohman23e62c52009-08-21 16:52:54 +0000942 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohman81ce8422009-08-19 18:18:36 +0000943 Ty = STy->getTypeAtIndex(ElIdx);
Dan Gohman81ce8422009-08-19 18:18:36 +0000944 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000945 } while (Ty != ResElemTy);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000946
947 // If we haven't used up the entire offset by descending the static
948 // type, then the offset is pointing into the middle of an indivisible
949 // member, so we can't simplify it.
950 if (Offset != 0)
Craig Topper9f008862014-04-15 04:59:12 +0000951 return nullptr;
Dan Gohman81ce8422009-08-19 18:18:36 +0000952
Peter Collingbourned93620b2016-11-10 22:34:55 +0000953 // Preserve the inrange index from the innermost GEP if possible. We must
954 // have calculated the same indices up to and including the inrange index.
955 Optional<unsigned> InRangeIndex;
956 if (Optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex())
957 if (SrcElemTy == InnermostGEP->getSourceElementType() &&
958 NewIdxs.size() > *LastIRIndex) {
959 InRangeIndex = LastIRIndex;
960 for (unsigned I = 0; I <= *LastIRIndex; ++I)
961 if (NewIdxs[I] != InnermostGEP->getOperand(I + 1)) {
962 InRangeIndex = None;
963 break;
964 }
965 }
966
Dan Gohman21c62162009-09-11 00:04:14 +0000967 // Create a GEP.
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000968 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs,
969 InBounds, InRangeIndex);
Matt Arsenault8c789092013-08-12 23:15:58 +0000970 assert(C->getType()->getPointerElementType() == Ty &&
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000971 "Computed GetElementPtr has unexpected type!");
Dan Gohman81ce8422009-08-19 18:18:36 +0000972
Dan Gohmanc59ba422009-08-19 22:46:59 +0000973 // If we ended up indexing a member with a type that doesn't match
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000974 // the type of what the original indices indexed, add a cast.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000975 if (Ty != ResElemTy)
976 C = FoldBitCast(C, ResTy, DL);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000977
978 return C;
Chris Lattner44d68b92007-01-31 00:51:48 +0000979}
980
Manuel Jacobe9024592016-01-21 06:33:22 +0000981/// Attempt to constant fold an instruction with the
982/// specified opcode and operands. If successful, the constant result is
983/// returned, if not, null is returned. Note that this function can fail when
984/// attempting to fold instructions like loads and stores, which have no
985/// constant expression form.
986///
Peter Collingbourned93620b2016-11-10 22:34:55 +0000987/// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/inrange
988/// etc information, due to only being passed an opcode and operands. Constant
Manuel Jacobe9024592016-01-21 06:33:22 +0000989/// folding using this function strips this information.
990///
David Majnemera926b3e2016-07-29 03:27:33 +0000991Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000992 ArrayRef<Constant *> Ops,
993 const DataLayout &DL,
994 const TargetLibraryInfo *TLI) {
David Majnemera926b3e2016-07-29 03:27:33 +0000995 Type *DestTy = InstOrCE->getType();
996
Manuel Jacobe9024592016-01-21 06:33:22 +0000997 // Handle easy binops first.
998 if (Instruction::isBinaryOp(Opcode))
999 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
1000
1001 if (Instruction::isCast(Opcode))
1002 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1003
David Majnemer17bdf442016-07-13 03:42:38 +00001004 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001005 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
1006 return C;
1007
Peter Collingbourned93620b2016-11-10 22:34:55 +00001008 return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), Ops[0],
1009 Ops.slice(1), GEP->isInBounds(),
1010 GEP->getInRangeIndex());
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001011 }
1012
David Majnemer57b94c82016-07-29 03:27:31 +00001013 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
1014 return CE->getWithOperands(Ops);
1015
Manuel Jacobe9024592016-01-21 06:33:22 +00001016 switch (Opcode) {
1017 default: return nullptr;
1018 case Instruction::ICmp:
1019 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
1020 case Instruction::Call:
David Majnemer90a97042016-07-13 04:22:12 +00001021 if (auto *F = dyn_cast<Function>(Ops.back()))
Manuel Jacobe9024592016-01-21 06:33:22 +00001022 if (canConstantFoldCallTo(F))
1023 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
1024 return nullptr;
1025 case Instruction::Select:
1026 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1027 case Instruction::ExtractElement:
1028 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1029 case Instruction::InsertElement:
1030 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1031 case Instruction::ShuffleVector:
1032 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Manuel Jacobe9024592016-01-21 06:33:22 +00001033 }
1034}
1035
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001036} // end anonymous namespace
Chris Lattner44d68b92007-01-31 00:51:48 +00001037
1038//===----------------------------------------------------------------------===//
1039// Constant Folding public APIs
1040//===----------------------------------------------------------------------===//
1041
David Majnemerd536f232016-07-29 03:27:26 +00001042namespace {
1043
1044Constant *
1045ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1046 const TargetLibraryInfo *TLI,
1047 SmallDenseMap<Constant *, Constant *> &FoldedOps) {
1048 if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1049 return nullptr;
1050
1051 SmallVector<Constant *, 8> Ops;
1052 for (const Use &NewU : C->operands()) {
1053 auto *NewC = cast<Constant>(&NewU);
1054 // Recursively fold the ConstantExpr's operands. If we have already folded
1055 // a ConstantExpr, we don't have to process it again.
1056 if (isa<ConstantVector>(NewC) || isa<ConstantExpr>(NewC)) {
1057 auto It = FoldedOps.find(NewC);
1058 if (It == FoldedOps.end()) {
1059 if (auto *FoldedC =
1060 ConstantFoldConstantImpl(NewC, DL, TLI, FoldedOps)) {
1061 NewC = FoldedC;
1062 FoldedOps.insert({NewC, FoldedC});
1063 } else {
1064 FoldedOps.insert({NewC, NewC});
1065 }
1066 } else {
1067 NewC = It->second;
1068 }
1069 }
1070 Ops.push_back(NewC);
1071 }
1072
1073 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1074 if (CE->isCompare())
1075 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1076 DL, TLI);
1077
David Majnemera926b3e2016-07-29 03:27:33 +00001078 return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI);
David Majnemerd536f232016-07-29 03:27:26 +00001079 }
1080
1081 assert(isa<ConstantVector>(C));
1082 return ConstantVector::get(Ops);
1083}
1084
1085} // end anonymous namespace
1086
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001087Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001088 const TargetLibraryInfo *TLI) {
Duncan Sands763dec02010-11-23 10:16:18 +00001089 // Handle PHI nodes quickly here...
David Majnemer90a97042016-07-13 04:22:12 +00001090 if (auto *PN = dyn_cast<PHINode>(I)) {
Craig Topper9f008862014-04-15 04:59:12 +00001091 Constant *CommonValue = nullptr;
John Criswell970af112005-10-27 16:00:10 +00001092
David Majnemerd536f232016-07-29 03:27:26 +00001093 SmallDenseMap<Constant *, Constant *> FoldedOps;
Pete Cooper833f34d2015-05-12 20:05:31 +00001094 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands763dec02010-11-23 10:16:18 +00001095 // If the incoming value is undef then skip it. Note that while we could
1096 // skip the value if it is equal to the phi node itself we choose not to
1097 // because that would break the rule that constant folding only applies if
1098 // all operands are constants.
1099 if (isa<UndefValue>(Incoming))
Duncan Sands1d27f0122010-11-14 12:53:18 +00001100 continue;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001101 // If the incoming value is not a constant, then give up.
David Majnemer90a97042016-07-13 04:22:12 +00001102 auto *C = dyn_cast<Constant>(Incoming);
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001103 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00001104 return nullptr;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001105 // Fold the PHI's operands.
David Majnemerd536f232016-07-29 03:27:26 +00001106 if (auto *FoldedC = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps))
1107 C = FoldedC;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001108 // If the incoming value is a different constant to
1109 // the one we saw previously, then give up.
1110 if (CommonValue && C != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00001111 return nullptr;
Duncan Sands1d27f0122010-11-14 12:53:18 +00001112 CommonValue = C;
1113 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001114
Duncan Sands1d27f0122010-11-14 12:53:18 +00001115 // If we reach here, all incoming values are the same constant or undef.
1116 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
Chris Lattner2ae054a2007-01-30 23:45:45 +00001117 }
1118
1119 // Scan the operand list, checking to see if they are all constants, if so,
Manuel Jacobe9024592016-01-21 06:33:22 +00001120 // hand off to ConstantFoldInstOperandsImpl.
Fiona Glaser2e5c0c22016-03-13 05:36:15 +00001121 if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1122 return nullptr;
Chris Lattner2ae054a2007-01-30 23:45:45 +00001123
David Majnemerd536f232016-07-29 03:27:26 +00001124 SmallDenseMap<Constant *, Constant *> FoldedOps;
Fiona Glaser2e5c0c22016-03-13 05:36:15 +00001125 SmallVector<Constant *, 8> Ops;
David Majnemer90a97042016-07-13 04:22:12 +00001126 for (const Use &OpU : I->operands()) {
1127 auto *Op = cast<Constant>(&OpU);
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001128 // Fold the Instruction's operands.
David Majnemerd536f232016-07-29 03:27:26 +00001129 if (auto *FoldedOp = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps))
1130 Op = FoldedOp;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001131
1132 Ops.push_back(Op);
1133 }
1134
David Majnemer90a97042016-07-13 04:22:12 +00001135 if (const auto *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001136 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001137 DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001138
David Majnemer90a97042016-07-13 04:22:12 +00001139 if (const auto *LI = dyn_cast<LoadInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001140 return ConstantFoldLoadInst(LI, DL);
Frits van Bommela98214d2010-11-29 20:36:52 +00001141
David Majnemer90a97042016-07-13 04:22:12 +00001142 if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001143 return ConstantExpr::getInsertValue(
1144 cast<Constant>(IVI->getAggregateOperand()),
1145 cast<Constant>(IVI->getInsertedValueOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001146 IVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001147 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001148
David Majnemer90a97042016-07-13 04:22:12 +00001149 if (auto *EVI = dyn_cast<ExtractValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001150 return ConstantExpr::getExtractValue(
1151 cast<Constant>(EVI->getAggregateOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001152 EVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001153 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001154
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001155 return ConstantFoldInstOperands(I, Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001156}
1157
David Majnemerd536f232016-07-29 03:27:26 +00001158Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL,
1159 const TargetLibraryInfo *TLI) {
1160 SmallDenseMap<Constant *, Constant *> FoldedOps;
1161 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +00001162}
1163
Manuel Jacobe9024592016-01-21 06:33:22 +00001164Constant *llvm::ConstantFoldInstOperands(Instruction *I,
Jay Foadf4b14a22011-07-19 13:32:40 +00001165 ArrayRef<Constant *> Ops,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001166 const DataLayout &DL,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001167 const TargetLibraryInfo *TLI) {
David Majnemera926b3e2016-07-29 03:27:33 +00001168 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001169}
1170
Chris Lattnerd2265b42007-12-10 22:53:04 +00001171Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001172 Constant *Ops0, Constant *Ops1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001173 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001174 const TargetLibraryInfo *TLI) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001175 // fold: icmp (inttoptr x), null -> icmp x, 0
1176 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001177 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd2265b42007-12-10 22:53:04 +00001178 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1179 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001180 // FIXME: The following comment is out of data and the DataLayout is here now.
1181 // ConstantExpr::getCompare cannot do this, because it doesn't have DL
Chris Lattnerd2265b42007-12-10 22:53:04 +00001182 // around to know if bit truncation is happening.
David Majnemer90a97042016-07-13 04:22:12 +00001183 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001184 if (Ops1->isNullValue()) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001185 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001186 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Chris Lattnerd2265b42007-12-10 22:53:04 +00001187 // Convert the integer value to the right size to ensure we get the
1188 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001189 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd2265b42007-12-10 22:53:04 +00001190 IntPtrTy, false);
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001191 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001192 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001193 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001194
Chris Lattnerd2265b42007-12-10 22:53:04 +00001195 // Only do this transformation if the int is intptrty in size, otherwise
1196 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001197 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001198 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001199 if (CE0->getType() == IntPtrTy) {
1200 Constant *C = CE0->getOperand(0);
1201 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001202 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001203 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001204 }
1205 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001206
David Majnemer90a97042016-07-13 04:22:12 +00001207 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001208 if (CE0->getOpcode() == CE1->getOpcode()) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001209 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001210 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001211
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001212 // Convert the integer value to the right size to ensure we get the
1213 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001214 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001215 IntPtrTy, false);
Owen Anderson487375e2009-07-29 18:55:55 +00001216 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001217 IntPtrTy, false);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001218 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001219 }
1220
Chandler Carruth7ec50852012-11-01 08:07:29 +00001221 // Only do this transformation if the int is intptrty in size, otherwise
1222 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001223 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001224 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001225 if (CE0->getType() == IntPtrTy &&
1226 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001227 return ConstantFoldCompareInstOperands(
1228 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001229 }
1230 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001231 }
1232 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001233
Chris Lattner8fb74c62010-01-02 01:22:23 +00001234 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1235 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1236 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1237 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001238 Constant *LHS = ConstantFoldCompareInstOperands(
1239 Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1240 Constant *RHS = ConstantFoldCompareInstOperands(
1241 Predicate, CE0->getOperand(1), Ops1, DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001242 unsigned OpC =
Chris Lattner8fb74c62010-01-02 01:22:23 +00001243 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
Manuel Jacoba61ca372016-01-21 06:26:35 +00001244 return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
Chris Lattner8fb74c62010-01-02 01:22:23 +00001245 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001246 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001247
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001248 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001249}
1250
Manuel Jacoba61ca372016-01-21 06:26:35 +00001251Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1252 Constant *RHS,
1253 const DataLayout &DL) {
1254 assert(Instruction::isBinaryOp(Opcode));
1255 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1256 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1257 return C;
1258
1259 return ConstantExpr::get(Opcode, LHS, RHS);
1260}
Chris Lattnerd2265b42007-12-10 22:53:04 +00001261
Manuel Jacob925d0292016-01-21 06:31:08 +00001262Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1263 Type *DestTy, const DataLayout &DL) {
1264 assert(Instruction::isCast(Opcode));
1265 switch (Opcode) {
1266 default:
1267 llvm_unreachable("Missing case");
1268 case Instruction::PtrToInt:
1269 // If the input is a inttoptr, eliminate the pair. This requires knowing
1270 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001271 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001272 if (CE->getOpcode() == Instruction::IntToPtr) {
1273 Constant *Input = CE->getOperand(0);
1274 unsigned InWidth = Input->getType()->getScalarSizeInBits();
1275 unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1276 if (PtrWidth < InWidth) {
1277 Constant *Mask =
1278 ConstantInt::get(CE->getContext(),
1279 APInt::getLowBitsSet(InWidth, PtrWidth));
1280 Input = ConstantExpr::getAnd(Input, Mask);
1281 }
1282 // Do a zext or trunc to get to the dest size.
1283 return ConstantExpr::getIntegerCast(Input, DestTy, false);
1284 }
1285 }
1286 return ConstantExpr::getCast(Opcode, C, DestTy);
1287 case Instruction::IntToPtr:
1288 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1289 // the int size is >= the ptr size and the address spaces are the same.
1290 // This requires knowing the width of a pointer, so it can't be done in
1291 // ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001292 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001293 if (CE->getOpcode() == Instruction::PtrToInt) {
1294 Constant *SrcPtr = CE->getOperand(0);
1295 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1296 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1297
1298 if (MidIntSize >= SrcPtrSize) {
1299 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1300 if (SrcAS == DestTy->getPointerAddressSpace())
1301 return FoldBitCast(CE->getOperand(0), DestTy, DL);
1302 }
1303 }
1304 }
1305
1306 return ConstantExpr::getCast(Opcode, C, DestTy);
1307 case Instruction::Trunc:
1308 case Instruction::ZExt:
1309 case Instruction::SExt:
1310 case Instruction::FPTrunc:
1311 case Instruction::FPExt:
1312 case Instruction::UIToFP:
1313 case Instruction::SIToFP:
1314 case Instruction::FPToUI:
1315 case Instruction::FPToSI:
1316 case Instruction::AddrSpaceCast:
1317 return ConstantExpr::getCast(Opcode, C, DestTy);
1318 case Instruction::BitCast:
1319 return FoldBitCast(C, DestTy, DL);
1320 }
1321}
1322
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001323Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmane525d9d2009-10-05 16:36:26 +00001324 ConstantExpr *CE) {
Chris Lattnerf488b352012-01-24 05:43:50 +00001325 if (!CE->getOperand(1)->isNullValue())
Craig Topper9f008862014-04-15 04:59:12 +00001326 return nullptr; // Do not allow stepping over the value!
Chris Lattner67058832012-01-25 06:48:06 +00001327
1328 // Loop over all of the operands, tracking down which value we are
1329 // addressing.
1330 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1331 C = C->getAggregateElement(CE->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00001332 if (!C)
1333 return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00001334 }
1335 return C;
Chris Lattnerf488b352012-01-24 05:43:50 +00001336}
1337
David Majnemer90a97042016-07-13 04:22:12 +00001338Constant *
1339llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1340 ArrayRef<Constant *> Indices) {
Chris Lattner2ae054a2007-01-30 23:45:45 +00001341 // Loop over all of the operands, tracking down which value we are
Chris Lattnerf488b352012-01-24 05:43:50 +00001342 // addressing.
David Majnemer90a97042016-07-13 04:22:12 +00001343 for (Constant *Index : Indices) {
1344 C = C->getAggregateElement(Index);
Craig Topper9f008862014-04-15 04:59:12 +00001345 if (!C)
1346 return nullptr;
Chris Lattnerf488b352012-01-24 05:43:50 +00001347 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001348 return C;
1349}
1350
Chris Lattner2ae054a2007-01-30 23:45:45 +00001351//===----------------------------------------------------------------------===//
1352// Constant Folding for Calls
1353//
John Criswell970af112005-10-27 16:00:10 +00001354
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001355bool llvm::canConstantFoldCallTo(const Function *F) {
John Criswell970af112005-10-27 16:00:10 +00001356 switch (F->getIntrinsicID()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001357 case Intrinsic::fabs:
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001358 case Intrinsic::minnum:
1359 case Intrinsic::maxnum:
Owen Andersond4ebfd82013-02-06 22:43:31 +00001360 case Intrinsic::log:
1361 case Intrinsic::log2:
1362 case Intrinsic::log10:
1363 case Intrinsic::exp:
1364 case Intrinsic::exp2:
1365 case Intrinsic::floor:
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001366 case Intrinsic::ceil:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001367 case Intrinsic::sqrt:
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001368 case Intrinsic::sin:
1369 case Intrinsic::cos:
Karthik Bhatd818e382015-07-21 08:52:23 +00001370 case Intrinsic::trunc:
1371 case Intrinsic::rint:
1372 case Intrinsic::nearbyint:
Chad Rosier0155a632011-12-03 00:00:03 +00001373 case Intrinsic::pow:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001374 case Intrinsic::powi:
Reid Spencer6bba6c82007-04-01 07:35:23 +00001375 case Intrinsic::bswap:
1376 case Intrinsic::ctpop:
1377 case Intrinsic::ctlz:
1378 case Intrinsic::cttz:
Matt Arsenault83778582014-03-05 00:02:00 +00001379 case Intrinsic::fma:
1380 case Intrinsic::fmuladd:
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001381 case Intrinsic::copysign:
Karthik Bhatb67688a2014-03-07 04:36:21 +00001382 case Intrinsic::round:
David Majnemer7f781ab2016-07-14 00:29:50 +00001383 case Intrinsic::masked_load:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001384 case Intrinsic::sadd_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001385 case Intrinsic::uadd_with_overflow:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001386 case Intrinsic::ssub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001387 case Intrinsic::usub_with_overflow:
Chris Lattner698661c2010-10-14 00:05:07 +00001388 case Intrinsic::smul_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001389 case Intrinsic::umul_with_overflow:
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001390 case Intrinsic::convert_from_fp16:
1391 case Intrinsic::convert_to_fp16:
Matt Arsenault155dda92016-03-21 15:00:35 +00001392 case Intrinsic::bitreverse:
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001393 case Intrinsic::x86_sse_cvtss2si:
1394 case Intrinsic::x86_sse_cvtss2si64:
1395 case Intrinsic::x86_sse_cvttss2si:
1396 case Intrinsic::x86_sse_cvttss2si64:
1397 case Intrinsic::x86_sse2_cvtsd2si:
1398 case Intrinsic::x86_sse2_cvtsd2si64:
1399 case Intrinsic::x86_sse2_cvttsd2si:
1400 case Intrinsic::x86_sse2_cvttsd2si64:
John Criswell970af112005-10-27 16:00:10 +00001401 return true;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001402 default:
1403 return false;
1404 case 0: break;
John Criswell970af112005-10-27 16:00:10 +00001405 }
1406
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001407 if (!F->hasName())
1408 return false;
Daniel Dunbarca414c72009-07-26 08:34:35 +00001409 StringRef Name = F->getName();
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001410
Chris Lattner785f9982007-08-08 06:55:43 +00001411 // In these cases, the check of the length is required. We don't want to
1412 // return true for a name like "cos\0blah" which strcmp would return equal to
1413 // "cos", but has length 8.
Daniel Dunbarca414c72009-07-26 08:34:35 +00001414 switch (Name[0]) {
Erik Schnetter5e93e282015-08-27 19:56:57 +00001415 default:
1416 return false;
Chris Lattner785f9982007-08-08 06:55:43 +00001417 case 'a':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001418 return Name == "acos" || Name == "asin" || Name == "atan" ||
1419 Name == "atan2" || Name == "acosf" || Name == "asinf" ||
1420 Name == "atanf" || Name == "atan2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001421 case 'c':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001422 return Name == "ceil" || Name == "cos" || Name == "cosh" ||
1423 Name == "ceilf" || Name == "cosf" || Name == "coshf";
Chris Lattner785f9982007-08-08 06:55:43 +00001424 case 'e':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001425 return Name == "exp" || Name == "exp2" || Name == "expf" || Name == "exp2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001426 case 'f':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001427 return Name == "fabs" || Name == "floor" || Name == "fmod" ||
1428 Name == "fabsf" || Name == "floorf" || Name == "fmodf";
Chris Lattner785f9982007-08-08 06:55:43 +00001429 case 'l':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001430 return Name == "log" || Name == "log10" || Name == "logf" ||
1431 Name == "log10f";
Chris Lattner785f9982007-08-08 06:55:43 +00001432 case 'p':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001433 return Name == "pow" || Name == "powf";
Bryant Wongb5e03b62016-12-26 14:29:29 +00001434 case 'r':
1435 return Name == "round" || Name == "roundf";
Chris Lattner785f9982007-08-08 06:55:43 +00001436 case 's':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001437 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
Erik Schnetter5e93e282015-08-27 19:56:57 +00001438 Name == "sinf" || Name == "sinhf" || Name == "sqrtf";
Chris Lattner785f9982007-08-08 06:55:43 +00001439 case 't':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001440 return Name == "tan" || Name == "tanh" || Name == "tanf" || Name == "tanhf";
John Criswell970af112005-10-27 16:00:10 +00001441 }
1442}
1443
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001444namespace {
1445
1446Constant *GetConstantFoldFPValue(double V, Type *Ty) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001447 if (Ty->isHalfTy()) {
1448 APFloat APF(V);
1449 bool unused;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001450 APF.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &unused);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001451 return ConstantFP::get(Ty->getContext(), APF);
1452 }
Chris Lattner351534f2009-10-05 05:06:24 +00001453 if (Ty->isFloatTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001454 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
Chris Lattner351534f2009-10-05 05:06:24 +00001455 if (Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001456 return ConstantFP::get(Ty->getContext(), APFloat(V));
Owen Andersond4ebfd82013-02-06 22:43:31 +00001457 llvm_unreachable("Can only constant fold half/float/double");
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001458}
1459
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001460/// Clear the floating-point exception state.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001461inline void llvm_fenv_clearexcept() {
Alp Toker51420a82014-06-09 19:00:52 +00001462#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001463 feclearexcept(FE_ALL_EXCEPT);
1464#endif
1465 errno = 0;
1466}
1467
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001468/// Test if a floating-point exception was raised.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001469inline bool llvm_fenv_testexcept() {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001470 int errno_val = errno;
1471 if (errno_val == ERANGE || errno_val == EDOM)
1472 return true;
Alp Toker51420a82014-06-09 19:00:52 +00001473#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001474 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1475 return true;
1476#endif
1477 return false;
1478}
Alp Tokerc817d6a2014-06-09 18:28:53 +00001479
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001480Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001481 llvm_fenv_clearexcept();
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001482 V = NativeFP(V);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001483 if (llvm_fenv_testexcept()) {
1484 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001485 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001486 }
1487
1488 return GetConstantFoldFPValue(V, Ty);
John Criswell970af112005-10-27 16:00:10 +00001489}
1490
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001491Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1492 double W, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001493 llvm_fenv_clearexcept();
Dan Gohman72efc042007-07-16 15:26:22 +00001494 V = NativeFP(V, W);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001495 if (llvm_fenv_testexcept()) {
1496 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001497 return nullptr;
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001498 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001499
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001500 return GetConstantFoldFPValue(V, Ty);
Dan Gohman72efc042007-07-16 15:26:22 +00001501}
1502
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001503/// Attempt to fold an SSE floating point to integer conversion of a constant
1504/// floating point. If roundTowardZero is false, the default IEEE rounding is
1505/// used (toward nearest, ties to even). This matches the behavior of the
1506/// non-truncating SSE instructions in the default rounding mode. The desired
1507/// integer type Ty is used to select how many bits are available for the
1508/// result. Returns null if the conversion cannot be performed, otherwise
1509/// returns the Constant value resulting from the conversion.
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001510Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
1511 Type *Ty) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001512 // All of these conversion intrinsics form an integer of at most 64bits.
Matt Arsenault8c789092013-08-12 23:15:58 +00001513 unsigned ResultWidth = Ty->getIntegerBitWidth();
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001514 assert(ResultWidth <= 64 &&
1515 "Can only constant fold conversions to 64 and 32 bit ints");
1516
1517 uint64_t UIntVal;
1518 bool isExact = false;
1519 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1520 : APFloat::rmNearestTiesToEven;
1521 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1522 /*isSigned=*/true, mode,
1523 &isExact);
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001524 if (status != APFloat::opOK &&
1525 (!roundTowardZero || status != APFloat::opInexact))
Craig Topper9f008862014-04-15 04:59:12 +00001526 return nullptr;
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001527 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1528}
1529
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001530double getValueAsDouble(ConstantFP *Op) {
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001531 Type *Ty = Op->getType();
1532
1533 if (Ty->isFloatTy())
1534 return Op->getValueAPF().convertToFloat();
1535
1536 if (Ty->isDoubleTy())
1537 return Op->getValueAPF().convertToDouble();
1538
1539 bool unused;
1540 APFloat APF = Op->getValueAPF();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001541 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001542 return APF.convertToDouble();
1543}
1544
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001545Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty,
1546 ArrayRef<Constant *> Operands,
1547 const TargetLibraryInfo *TLI) {
Jay Foadf4b14a22011-07-19 13:32:40 +00001548 if (Operands.size() == 1) {
Sanjoy Das87b9e1b2016-04-08 18:21:11 +00001549 if (isa<UndefValue>(Operands[0])) {
1550 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN
1551 if (IntrinsicID == Intrinsic::cos)
1552 return Constant::getNullValue(Ty);
1553 }
David Majnemer90a97042016-07-13 04:22:12 +00001554 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001555 if (IntrinsicID == Intrinsic::convert_to_fp16) {
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001556 APFloat Val(Op->getValueAPF());
1557
1558 bool lost = false;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001559 Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001560
Benjamin Kramer061d1472014-03-05 19:41:48 +00001561 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001562 }
1563
Owen Andersond4ebfd82013-02-06 22:43:31 +00001564 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001565 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001566
Karthik Bhatb67688a2014-03-07 04:36:21 +00001567 if (IntrinsicID == Intrinsic::round) {
1568 APFloat V = Op->getValueAPF();
1569 V.roundToIntegral(APFloat::rmNearestTiesToAway);
1570 return ConstantFP::get(Ty->getContext(), V);
1571 }
1572
Karthik Bhatd818e382015-07-21 08:52:23 +00001573 if (IntrinsicID == Intrinsic::floor) {
1574 APFloat V = Op->getValueAPF();
1575 V.roundToIntegral(APFloat::rmTowardNegative);
1576 return ConstantFP::get(Ty->getContext(), V);
1577 }
1578
1579 if (IntrinsicID == Intrinsic::ceil) {
1580 APFloat V = Op->getValueAPF();
1581 V.roundToIntegral(APFloat::rmTowardPositive);
1582 return ConstantFP::get(Ty->getContext(), V);
1583 }
1584
1585 if (IntrinsicID == Intrinsic::trunc) {
1586 APFloat V = Op->getValueAPF();
1587 V.roundToIntegral(APFloat::rmTowardZero);
1588 return ConstantFP::get(Ty->getContext(), V);
1589 }
1590
1591 if (IntrinsicID == Intrinsic::rint) {
1592 APFloat V = Op->getValueAPF();
1593 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1594 return ConstantFP::get(Ty->getContext(), V);
1595 }
1596
1597 if (IntrinsicID == Intrinsic::nearbyint) {
1598 APFloat V = Op->getValueAPF();
1599 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1600 return ConstantFP::get(Ty->getContext(), V);
1601 }
1602
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001603 /// We only fold functions with finite arguments. Folding NaN and inf is
1604 /// likely to be aborted with an exception anyway, and some host libms
1605 /// have known errors raising exceptions.
1606 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
Craig Topper9f008862014-04-15 04:59:12 +00001607 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001608
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001609 /// Currently APFloat versions of these functions do not exist, so we use
1610 /// the host native double versions. Float versions are not called
1611 /// directly but for all these it is true (float)(f((double)arg)) ==
1612 /// f(arg). Long double not supported yet.
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001613 double V = getValueAsDouble(Op);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001614
Benjamin Kramer061d1472014-03-05 19:41:48 +00001615 switch (IntrinsicID) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001616 default: break;
1617 case Intrinsic::fabs:
1618 return ConstantFoldFP(fabs, V, Ty);
1619 case Intrinsic::log2:
Vince Harrond5281122015-05-07 00:05:26 +00001620 return ConstantFoldFP(Log2, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001621 case Intrinsic::log:
1622 return ConstantFoldFP(log, V, Ty);
1623 case Intrinsic::log10:
1624 return ConstantFoldFP(log10, V, Ty);
1625 case Intrinsic::exp:
1626 return ConstantFoldFP(exp, V, Ty);
1627 case Intrinsic::exp2:
1628 return ConstantFoldFP(exp2, V, Ty);
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001629 case Intrinsic::sin:
1630 return ConstantFoldFP(sin, V, Ty);
1631 case Intrinsic::cos:
1632 return ConstantFoldFP(cos, V, Ty);
Justin Lebar8b18a342017-01-21 00:59:57 +00001633 case Intrinsic::sqrt:
1634 return ConstantFoldFP(sqrt, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001635 }
1636
Benjamin Kramer061d1472014-03-05 19:41:48 +00001637 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001638 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001639
Daniel Dunbarca414c72009-07-26 08:34:35 +00001640 switch (Name[0]) {
Chris Lattner785f9982007-08-08 06:55:43 +00001641 case 'a':
David L. Jonesd21529f2017-01-23 23:16:46 +00001642 if ((Name == "acos" && TLI->has(LibFunc_acos)) ||
1643 (Name == "acosf" && TLI->has(LibFunc_acosf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001644 return ConstantFoldFP(acos, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001645 else if ((Name == "asin" && TLI->has(LibFunc_asin)) ||
1646 (Name == "asinf" && TLI->has(LibFunc_asinf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001647 return ConstantFoldFP(asin, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001648 else if ((Name == "atan" && TLI->has(LibFunc_atan)) ||
1649 (Name == "atanf" && TLI->has(LibFunc_atanf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001650 return ConstantFoldFP(atan, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001651 break;
1652 case 'c':
David L. Jonesd21529f2017-01-23 23:16:46 +00001653 if ((Name == "ceil" && TLI->has(LibFunc_ceil)) ||
1654 (Name == "ceilf" && TLI->has(LibFunc_ceilf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001655 return ConstantFoldFP(ceil, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001656 else if ((Name == "cos" && TLI->has(LibFunc_cos)) ||
1657 (Name == "cosf" && TLI->has(LibFunc_cosf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001658 return ConstantFoldFP(cos, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001659 else if ((Name == "cosh" && TLI->has(LibFunc_cosh)) ||
1660 (Name == "coshf" && TLI->has(LibFunc_coshf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001661 return ConstantFoldFP(cosh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001662 break;
1663 case 'e':
David L. Jonesd21529f2017-01-23 23:16:46 +00001664 if ((Name == "exp" && TLI->has(LibFunc_exp)) ||
1665 (Name == "expf" && TLI->has(LibFunc_expf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001666 return ConstantFoldFP(exp, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001667 if ((Name == "exp2" && TLI->has(LibFunc_exp2)) ||
1668 (Name == "exp2f" && TLI->has(LibFunc_exp2f)))
Chris Lattner713d5232011-05-22 22:22:35 +00001669 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1670 // C99 library.
1671 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001672 break;
1673 case 'f':
David L. Jonesd21529f2017-01-23 23:16:46 +00001674 if ((Name == "fabs" && TLI->has(LibFunc_fabs)) ||
1675 (Name == "fabsf" && TLI->has(LibFunc_fabsf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001676 return ConstantFoldFP(fabs, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001677 else if ((Name == "floor" && TLI->has(LibFunc_floor)) ||
1678 (Name == "floorf" && TLI->has(LibFunc_floorf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001679 return ConstantFoldFP(floor, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001680 break;
1681 case 'l':
David L. Jonesd21529f2017-01-23 23:16:46 +00001682 if ((Name == "log" && V > 0 && TLI->has(LibFunc_log)) ||
1683 (Name == "logf" && V > 0 && TLI->has(LibFunc_logf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001684 return ConstantFoldFP(log, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001685 else if ((Name == "log10" && V > 0 && TLI->has(LibFunc_log10)) ||
1686 (Name == "log10f" && V > 0 && TLI->has(LibFunc_log10f)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001687 return ConstantFoldFP(log10, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001688 break;
Bryant Wongb5e03b62016-12-26 14:29:29 +00001689 case 'r':
David L. Jonesd21529f2017-01-23 23:16:46 +00001690 if ((Name == "round" && TLI->has(LibFunc_round)) ||
1691 (Name == "roundf" && TLI->has(LibFunc_roundf)))
Bryant Wongb5e03b62016-12-26 14:29:29 +00001692 return ConstantFoldFP(round, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001693 case 's':
David L. Jonesd21529f2017-01-23 23:16:46 +00001694 if ((Name == "sin" && TLI->has(LibFunc_sin)) ||
1695 (Name == "sinf" && TLI->has(LibFunc_sinf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001696 return ConstantFoldFP(sin, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001697 else if ((Name == "sinh" && TLI->has(LibFunc_sinh)) ||
1698 (Name == "sinhf" && TLI->has(LibFunc_sinhf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001699 return ConstantFoldFP(sinh, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001700 else if ((Name == "sqrt" && V >= 0 && TLI->has(LibFunc_sqrt)) ||
1701 (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc_sqrtf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001702 return ConstantFoldFP(sqrt, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001703 break;
1704 case 't':
David L. Jonesd21529f2017-01-23 23:16:46 +00001705 if ((Name == "tan" && TLI->has(LibFunc_tan)) ||
1706 (Name == "tanf" && TLI->has(LibFunc_tanf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001707 return ConstantFoldFP(tan, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001708 else if ((Name == "tanh" && TLI->has(LibFunc_tanh)) ||
1709 (Name == "tanhf" && TLI->has(LibFunc_tanhf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001710 return ConstantFoldFP(tanh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001711 break;
1712 default:
1713 break;
John Criswell970af112005-10-27 16:00:10 +00001714 }
Craig Topper9f008862014-04-15 04:59:12 +00001715 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001716 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001717
David Majnemer90a97042016-07-13 04:22:12 +00001718 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001719 switch (IntrinsicID) {
Chandler Carruth352d9b12011-01-10 09:02:58 +00001720 case Intrinsic::bswap:
Benjamin Kramer061d1472014-03-05 19:41:48 +00001721 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001722 case Intrinsic::ctpop:
Owen Andersonedb4a702009-07-24 23:12:02 +00001723 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Matt Arsenault155dda92016-03-21 15:00:35 +00001724 case Intrinsic::bitreverse:
1725 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001726 case Intrinsic::convert_from_fp16: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001727 APFloat Val(APFloat::IEEEhalf(), Op->getValue());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001728
1729 bool lost = false;
Andrea Di Biagio29059992015-05-14 18:01:48 +00001730 APFloat::opStatus status = Val.convert(
1731 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001732
1733 // Conversion is always precise.
Jeffrey Yasskin9b43f332010-12-23 00:58:24 +00001734 (void)status;
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001735 assert(status == APFloat::opOK && !lost &&
1736 "Precision lost during fp16 constfolding");
1737
Benjamin Kramer061d1472014-03-05 19:41:48 +00001738 return ConstantFP::get(Ty->getContext(), Val);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001739 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001740 default:
Craig Topper9f008862014-04-15 04:59:12 +00001741 return nullptr;
Chandler Carruth352d9b12011-01-10 09:02:58 +00001742 }
John Criswell970af112005-10-27 16:00:10 +00001743 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001744
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001745 // Support ConstantVector in case we have an Undef in the top.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001746 if (isa<ConstantVector>(Operands[0]) ||
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001747 isa<ConstantDataVector>(Operands[0])) {
David Majnemer90a97042016-07-13 04:22:12 +00001748 auto *Op = cast<Constant>(Operands[0]);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001749 switch (IntrinsicID) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001750 default: break;
1751 case Intrinsic::x86_sse_cvtss2si:
1752 case Intrinsic::x86_sse_cvtss2si64:
1753 case Intrinsic::x86_sse2_cvtsd2si:
1754 case Intrinsic::x86_sse2_cvtsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001755 if (ConstantFP *FPOp =
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001756 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1757 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1758 /*roundTowardZero=*/false, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001759 case Intrinsic::x86_sse_cvttss2si:
1760 case Intrinsic::x86_sse_cvttss2si64:
1761 case Intrinsic::x86_sse2_cvttsd2si:
1762 case Intrinsic::x86_sse2_cvttsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001763 if (ConstantFP *FPOp =
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001764 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1765 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1766 /*roundTowardZero=*/true, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001767 }
1768 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001769
Dan Gohmancf39be32010-02-17 00:54:58 +00001770 if (isa<UndefValue>(Operands[0])) {
Brian Gesiak1640e682017-03-19 04:40:42 +00001771 if (IntrinsicID == Intrinsic::bswap ||
1772 IntrinsicID == Intrinsic::bitreverse)
Dan Gohmancf39be32010-02-17 00:54:58 +00001773 return Operands[0];
Craig Topper9f008862014-04-15 04:59:12 +00001774 return nullptr;
Dan Gohmancf39be32010-02-17 00:54:58 +00001775 }
1776
Craig Topper9f008862014-04-15 04:59:12 +00001777 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001778 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001779
Jay Foadf4b14a22011-07-19 13:32:40 +00001780 if (Operands.size() == 2) {
David Majnemer90a97042016-07-13 04:22:12 +00001781 if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001782 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001783 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001784 double Op1V = getValueAsDouble(Op1);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001785
David Majnemer90a97042016-07-13 04:22:12 +00001786 if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattner351534f2009-10-05 05:06:24 +00001787 if (Op2->getType() != Op1->getType())
Craig Topper9f008862014-04-15 04:59:12 +00001788 return nullptr;
Chad Rosier576c0f82011-12-01 23:16:03 +00001789
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001790 double Op2V = getValueAsDouble(Op2);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001791 if (IntrinsicID == Intrinsic::pow) {
Chad Rosier0155a632011-12-03 00:00:03 +00001792 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1793 }
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001794 if (IntrinsicID == Intrinsic::copysign) {
1795 APFloat V1 = Op1->getValueAPF();
Benjamin Kramer8f59adb2016-02-13 16:54:14 +00001796 const APFloat &V2 = Op2->getValueAPF();
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001797 V1.copySign(V2);
1798 return ConstantFP::get(Ty->getContext(), V1);
1799 }
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001800
1801 if (IntrinsicID == Intrinsic::minnum) {
1802 const APFloat &C1 = Op1->getValueAPF();
1803 const APFloat &C2 = Op2->getValueAPF();
1804 return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1805 }
1806
1807 if (IntrinsicID == Intrinsic::maxnum) {
1808 const APFloat &C1 = Op1->getValueAPF();
1809 const APFloat &C2 = Op2->getValueAPF();
1810 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1811 }
1812
Chad Rosier0155a632011-12-03 00:00:03 +00001813 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001814 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00001815 if ((Name == "pow" && TLI->has(LibFunc_pow)) ||
1816 (Name == "powf" && TLI->has(LibFunc_powf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001817 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001818 if ((Name == "fmod" && TLI->has(LibFunc_fmod)) ||
1819 (Name == "fmodf" && TLI->has(LibFunc_fmodf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001820 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001821 if ((Name == "atan2" && TLI->has(LibFunc_atan2)) ||
1822 (Name == "atan2f" && TLI->has(LibFunc_atan2f)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001823 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
David Majnemer90a97042016-07-13 04:22:12 +00001824 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001825 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1826 return ConstantFP::get(Ty->getContext(),
Owen Andersond4ebfd82013-02-06 22:43:31 +00001827 APFloat((float)std::pow((float)Op1V,
1828 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001829 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1830 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001831 APFloat((float)std::pow((float)Op1V,
Chris Lattner3b187622008-04-20 00:41:09 +00001832 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001833 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1834 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001835 APFloat((double)std::pow((double)Op1V,
1836 (int)Op2C->getZExtValue())));
John Criswell970af112005-10-27 16:00:10 +00001837 }
Craig Topper9f008862014-04-15 04:59:12 +00001838 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001839 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001840
David Majnemer90a97042016-07-13 04:22:12 +00001841 if (auto *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1842 if (auto *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001843 switch (IntrinsicID) {
Chris Lattner59d93982009-10-05 05:26:04 +00001844 default: break;
Chris Lattner698661c2010-10-14 00:05:07 +00001845 case Intrinsic::sadd_with_overflow:
1846 case Intrinsic::uadd_with_overflow:
1847 case Intrinsic::ssub_with_overflow:
1848 case Intrinsic::usub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001849 case Intrinsic::smul_with_overflow:
1850 case Intrinsic::umul_with_overflow: {
Chris Lattner698661c2010-10-14 00:05:07 +00001851 APInt Res;
1852 bool Overflow;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001853 switch (IntrinsicID) {
Craig Toppera2886c22012-02-07 05:05:23 +00001854 default: llvm_unreachable("Invalid case");
Chris Lattner698661c2010-10-14 00:05:07 +00001855 case Intrinsic::sadd_with_overflow:
1856 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1857 break;
1858 case Intrinsic::uadd_with_overflow:
1859 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1860 break;
1861 case Intrinsic::ssub_with_overflow:
1862 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1863 break;
1864 case Intrinsic::usub_with_overflow:
1865 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1866 break;
1867 case Intrinsic::smul_with_overflow:
1868 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1869 break;
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001870 case Intrinsic::umul_with_overflow:
1871 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1872 break;
Chris Lattner698661c2010-10-14 00:05:07 +00001873 }
Chris Lattner59d93982009-10-05 05:26:04 +00001874 Constant *Ops[] = {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001875 ConstantInt::get(Ty->getContext(), Res),
1876 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
Chris Lattner59d93982009-10-05 05:26:04 +00001877 };
Benjamin Kramer061d1472014-03-05 19:41:48 +00001878 return ConstantStruct::get(cast<StructType>(Ty), Ops);
Chris Lattner59d93982009-10-05 05:26:04 +00001879 }
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001880 case Intrinsic::cttz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001881 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1882 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001883 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1884 case Intrinsic::ctlz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001885 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1886 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001887 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
Chris Lattner59d93982009-10-05 05:26:04 +00001888 }
1889 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001890
Craig Topper9f008862014-04-15 04:59:12 +00001891 return nullptr;
Chris Lattner59d93982009-10-05 05:26:04 +00001892 }
Craig Topper9f008862014-04-15 04:59:12 +00001893 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001894 }
Matt Arsenault83778582014-03-05 00:02:00 +00001895
1896 if (Operands.size() != 3)
Craig Topper9f008862014-04-15 04:59:12 +00001897 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001898
David Majnemer90a97042016-07-13 04:22:12 +00001899 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1900 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1901 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001902 switch (IntrinsicID) {
Matt Arsenault83778582014-03-05 00:02:00 +00001903 default: break;
1904 case Intrinsic::fma:
1905 case Intrinsic::fmuladd: {
1906 APFloat V = Op1->getValueAPF();
1907 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1908 Op3->getValueAPF(),
1909 APFloat::rmNearestTiesToEven);
1910 if (s != APFloat::opInvalidOp)
1911 return ConstantFP::get(Ty->getContext(), V);
1912
Craig Topper9f008862014-04-15 04:59:12 +00001913 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001914 }
1915 }
1916 }
1917 }
1918 }
1919
Craig Topper9f008862014-04-15 04:59:12 +00001920 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001921}
Benjamin Kramer061d1472014-03-05 19:41:48 +00001922
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001923Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1924 VectorType *VTy, ArrayRef<Constant *> Operands,
David Majnemer7f781ab2016-07-14 00:29:50 +00001925 const DataLayout &DL,
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001926 const TargetLibraryInfo *TLI) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001927 SmallVector<Constant *, 4> Result(VTy->getNumElements());
1928 SmallVector<Constant *, 4> Lane(Operands.size());
1929 Type *Ty = VTy->getElementType();
1930
David Majnemer7f781ab2016-07-14 00:29:50 +00001931 if (IntrinsicID == Intrinsic::masked_load) {
1932 auto *SrcPtr = Operands[0];
1933 auto *Mask = Operands[2];
1934 auto *Passthru = Operands[3];
David Majnemer17a95aa2016-07-14 06:58:37 +00001935
David Majnemer7f781ab2016-07-14 00:29:50 +00001936 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, VTy, DL);
David Majnemer7f781ab2016-07-14 00:29:50 +00001937
1938 SmallVector<Constant *, 32> NewElements;
1939 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
David Majnemer17a95aa2016-07-14 06:58:37 +00001940 auto *MaskElt = Mask->getAggregateElement(I);
David Majnemer7f781ab2016-07-14 00:29:50 +00001941 if (!MaskElt)
1942 break;
David Majnemer17a95aa2016-07-14 06:58:37 +00001943 auto *PassthruElt = Passthru->getAggregateElement(I);
1944 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
1945 if (isa<UndefValue>(MaskElt)) {
1946 if (PassthruElt)
1947 NewElements.push_back(PassthruElt);
1948 else if (VecElt)
1949 NewElements.push_back(VecElt);
1950 else
1951 return nullptr;
1952 }
1953 if (MaskElt->isNullValue()) {
David Majnemer7f781ab2016-07-14 00:29:50 +00001954 if (!PassthruElt)
David Majnemer17a95aa2016-07-14 06:58:37 +00001955 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00001956 NewElements.push_back(PassthruElt);
David Majnemer17a95aa2016-07-14 06:58:37 +00001957 } else if (MaskElt->isOneValue()) {
David Majnemer7f781ab2016-07-14 00:29:50 +00001958 if (!VecElt)
David Majnemer17a95aa2016-07-14 06:58:37 +00001959 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00001960 NewElements.push_back(VecElt);
David Majnemer17a95aa2016-07-14 06:58:37 +00001961 } else {
1962 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00001963 }
1964 }
David Majnemer17a95aa2016-07-14 06:58:37 +00001965 if (NewElements.size() != VTy->getNumElements())
1966 return nullptr;
1967 return ConstantVector::get(NewElements);
David Majnemer7f781ab2016-07-14 00:29:50 +00001968 }
1969
Benjamin Kramer061d1472014-03-05 19:41:48 +00001970 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1971 // Gather a column of constants.
1972 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1973 Constant *Agg = Operands[J]->getAggregateElement(I);
1974 if (!Agg)
1975 return nullptr;
1976
1977 Lane[J] = Agg;
1978 }
1979
1980 // Use the regular scalar folding to simplify this column.
1981 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1982 if (!Folded)
1983 return nullptr;
1984 Result[I] = Folded;
1985 }
1986
1987 return ConstantVector::get(Result);
1988}
1989
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001990} // end anonymous namespace
1991
Benjamin Kramer061d1472014-03-05 19:41:48 +00001992Constant *
1993llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1994 const TargetLibraryInfo *TLI) {
1995 if (!F->hasName())
Craig Topper9f008862014-04-15 04:59:12 +00001996 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001997 StringRef Name = F->getName();
1998
1999 Type *Ty = F->getReturnType();
2000
David Majnemer90a97042016-07-13 04:22:12 +00002001 if (auto *VTy = dyn_cast<VectorType>(Ty))
David Majnemer7f781ab2016-07-14 00:29:50 +00002002 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands,
2003 F->getParent()->getDataLayout(), TLI);
Benjamin Kramer061d1472014-03-05 19:41:48 +00002004
2005 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
2006}
Eli Friedmanb6befc32016-11-02 20:48:11 +00002007
2008bool llvm::isMathLibCallNoop(CallSite CS, const TargetLibraryInfo *TLI) {
2009 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
2010 // (and to some extent ConstantFoldScalarCall).
2011 Function *F = CS.getCalledFunction();
2012 if (!F)
2013 return false;
2014
David L. Jonesd21529f2017-01-23 23:16:46 +00002015 LibFunc Func;
Eli Friedmanb6befc32016-11-02 20:48:11 +00002016 if (!TLI || !TLI->getLibFunc(*F, Func))
2017 return false;
2018
2019 if (CS.getNumArgOperands() == 1) {
2020 if (ConstantFP *OpC = dyn_cast<ConstantFP>(CS.getArgOperand(0))) {
2021 const APFloat &Op = OpC->getValueAPF();
2022 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002023 case LibFunc_logl:
2024 case LibFunc_log:
2025 case LibFunc_logf:
2026 case LibFunc_log2l:
2027 case LibFunc_log2:
2028 case LibFunc_log2f:
2029 case LibFunc_log10l:
2030 case LibFunc_log10:
2031 case LibFunc_log10f:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002032 return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
2033
David L. Jonesd21529f2017-01-23 23:16:46 +00002034 case LibFunc_expl:
2035 case LibFunc_exp:
2036 case LibFunc_expf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002037 // FIXME: These boundaries are slightly conservative.
2038 if (OpC->getType()->isDoubleTy())
2039 return Op.compare(APFloat(-745.0)) != APFloat::cmpLessThan &&
2040 Op.compare(APFloat(709.0)) != APFloat::cmpGreaterThan;
2041 if (OpC->getType()->isFloatTy())
2042 return Op.compare(APFloat(-103.0f)) != APFloat::cmpLessThan &&
2043 Op.compare(APFloat(88.0f)) != APFloat::cmpGreaterThan;
2044 break;
2045
David L. Jonesd21529f2017-01-23 23:16:46 +00002046 case LibFunc_exp2l:
2047 case LibFunc_exp2:
2048 case LibFunc_exp2f:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002049 // FIXME: These boundaries are slightly conservative.
2050 if (OpC->getType()->isDoubleTy())
2051 return Op.compare(APFloat(-1074.0)) != APFloat::cmpLessThan &&
2052 Op.compare(APFloat(1023.0)) != APFloat::cmpGreaterThan;
2053 if (OpC->getType()->isFloatTy())
2054 return Op.compare(APFloat(-149.0f)) != APFloat::cmpLessThan &&
2055 Op.compare(APFloat(127.0f)) != APFloat::cmpGreaterThan;
2056 break;
2057
David L. Jonesd21529f2017-01-23 23:16:46 +00002058 case LibFunc_sinl:
2059 case LibFunc_sin:
2060 case LibFunc_sinf:
2061 case LibFunc_cosl:
2062 case LibFunc_cos:
2063 case LibFunc_cosf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002064 return !Op.isInfinity();
2065
David L. Jonesd21529f2017-01-23 23:16:46 +00002066 case LibFunc_tanl:
2067 case LibFunc_tan:
2068 case LibFunc_tanf: {
Eli Friedmanb6befc32016-11-02 20:48:11 +00002069 // FIXME: Stop using the host math library.
2070 // FIXME: The computation isn't done in the right precision.
2071 Type *Ty = OpC->getType();
2072 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2073 double OpV = getValueAsDouble(OpC);
2074 return ConstantFoldFP(tan, OpV, Ty) != nullptr;
2075 }
2076 break;
2077 }
2078
David L. Jonesd21529f2017-01-23 23:16:46 +00002079 case LibFunc_asinl:
2080 case LibFunc_asin:
2081 case LibFunc_asinf:
2082 case LibFunc_acosl:
2083 case LibFunc_acos:
2084 case LibFunc_acosf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002085 return Op.compare(APFloat(Op.getSemantics(), "-1")) !=
2086 APFloat::cmpLessThan &&
2087 Op.compare(APFloat(Op.getSemantics(), "1")) !=
2088 APFloat::cmpGreaterThan;
2089
David L. Jonesd21529f2017-01-23 23:16:46 +00002090 case LibFunc_sinh:
2091 case LibFunc_cosh:
2092 case LibFunc_sinhf:
2093 case LibFunc_coshf:
2094 case LibFunc_sinhl:
2095 case LibFunc_coshl:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002096 // FIXME: These boundaries are slightly conservative.
2097 if (OpC->getType()->isDoubleTy())
2098 return Op.compare(APFloat(-710.0)) != APFloat::cmpLessThan &&
2099 Op.compare(APFloat(710.0)) != APFloat::cmpGreaterThan;
2100 if (OpC->getType()->isFloatTy())
2101 return Op.compare(APFloat(-89.0f)) != APFloat::cmpLessThan &&
2102 Op.compare(APFloat(89.0f)) != APFloat::cmpGreaterThan;
2103 break;
2104
David L. Jonesd21529f2017-01-23 23:16:46 +00002105 case LibFunc_sqrtl:
2106 case LibFunc_sqrt:
2107 case LibFunc_sqrtf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002108 return Op.isNaN() || Op.isZero() || !Op.isNegative();
2109
2110 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
2111 // maybe others?
2112 default:
2113 break;
2114 }
2115 }
2116 }
2117
2118 if (CS.getNumArgOperands() == 2) {
2119 ConstantFP *Op0C = dyn_cast<ConstantFP>(CS.getArgOperand(0));
2120 ConstantFP *Op1C = dyn_cast<ConstantFP>(CS.getArgOperand(1));
2121 if (Op0C && Op1C) {
2122 const APFloat &Op0 = Op0C->getValueAPF();
2123 const APFloat &Op1 = Op1C->getValueAPF();
2124
2125 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002126 case LibFunc_powl:
2127 case LibFunc_pow:
2128 case LibFunc_powf: {
Eli Friedmanb6befc32016-11-02 20:48:11 +00002129 // FIXME: Stop using the host math library.
2130 // FIXME: The computation isn't done in the right precision.
2131 Type *Ty = Op0C->getType();
2132 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2133 if (Ty == Op1C->getType()) {
2134 double Op0V = getValueAsDouble(Op0C);
2135 double Op1V = getValueAsDouble(Op1C);
2136 return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr;
2137 }
2138 }
2139 break;
2140 }
2141
David L. Jonesd21529f2017-01-23 23:16:46 +00002142 case LibFunc_fmodl:
2143 case LibFunc_fmod:
2144 case LibFunc_fmodf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002145 return Op0.isNaN() || Op1.isNaN() ||
2146 (!Op0.isInfinity() && !Op1.isZero());
2147
2148 default:
2149 break;
2150 }
2151 }
2152 }
2153
2154 return false;
2155}