Bitcasts are transitive. Bitcast-Bitcast-X becomes Bitcast-X.
[oota-llvm.git] / lib / Analysis / ConstantFolding.cpp
1 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines routines for folding instructions into constants.
11 //
12 // Also, to supplement the basic VMCore ConstantExpr simplifications,
13 // this file defines some additional folding routines that can make use of
14 // TargetData information. These functions cannot go in VMCore due to library
15 // dependency issues.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/GetElementPtrTypeIterator.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/FEnv.h"
35 #include <cerrno>
36 #include <cmath>
37 using namespace llvm;
38
39 //===----------------------------------------------------------------------===//
40 // Constant Folding internal helper functions
41 //===----------------------------------------------------------------------===//
42
43 /// FoldBitCast - Constant fold bitcast, symbolically evaluating it with 
44 /// TargetData.  This always returns a non-null constant, but it may be a
45 /// ConstantExpr if unfoldable.
46 static Constant *FoldBitCast(Constant *C, Type *DestTy,
47                              const TargetData &TD) {
48   // Catch the obvious splat cases.
49   if (C->isNullValue() && !DestTy->isX86_MMXTy())
50     return Constant::getNullValue(DestTy);
51   if (C->isAllOnesValue() && !DestTy->isX86_MMXTy())
52     return Constant::getAllOnesValue(DestTy);
53
54   // Bitcast of Bitcast can be done using a single cast.
55   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
56   if (CE && CE->getOpcode() == Instruction::BitCast) {
57     return ConstantExpr::getBitCast(CE->getOperand(0), DestTy);
58   }
59
60   // The code below only handles casts to vectors currently.
61   VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
62   if (DestVTy == 0)
63     return ConstantExpr::getBitCast(C, DestTy);
64   
65   // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
66   // vector so the code below can handle it uniformly.
67   if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
68     Constant *Ops = C; // don't take the address of C!
69     return FoldBitCast(ConstantVector::get(Ops), DestTy, TD);
70   }
71   
72   // If this is a bitcast from constant vector -> vector, fold it.
73   ConstantVector *CV = dyn_cast<ConstantVector>(C);
74   if (CV == 0)
75     return ConstantExpr::getBitCast(C, DestTy);
76   
77   // If the element types match, VMCore can fold it.
78   unsigned NumDstElt = DestVTy->getNumElements();
79   unsigned NumSrcElt = CV->getNumOperands();
80   if (NumDstElt == NumSrcElt)
81     return ConstantExpr::getBitCast(C, DestTy);
82   
83   Type *SrcEltTy = CV->getType()->getElementType();
84   Type *DstEltTy = DestVTy->getElementType();
85   
86   // Otherwise, we're changing the number of elements in a vector, which 
87   // requires endianness information to do the right thing.  For example,
88   //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
89   // folds to (little endian):
90   //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
91   // and to (big endian):
92   //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
93   
94   // First thing is first.  We only want to think about integer here, so if
95   // we have something in FP form, recast it as integer.
96   if (DstEltTy->isFloatingPointTy()) {
97     // Fold to an vector of integers with same size as our FP type.
98     unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
99     Type *DestIVTy =
100       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
101     // Recursively handle this integer conversion, if possible.
102     C = FoldBitCast(C, DestIVTy, TD);
103     if (!C) return ConstantExpr::getBitCast(C, DestTy);
104     
105     // Finally, VMCore can handle this now that #elts line up.
106     return ConstantExpr::getBitCast(C, DestTy);
107   }
108   
109   // Okay, we know the destination is integer, if the input is FP, convert
110   // it to integer first.
111   if (SrcEltTy->isFloatingPointTy()) {
112     unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
113     Type *SrcIVTy =
114       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
115     // Ask VMCore to do the conversion now that #elts line up.
116     C = ConstantExpr::getBitCast(C, SrcIVTy);
117     CV = dyn_cast<ConstantVector>(C);
118     if (!CV)  // If VMCore wasn't able to fold it, bail out.
119       return C;
120   }
121   
122   // Now we know that the input and output vectors are both integer vectors
123   // of the same size, and that their #elements is not the same.  Do the
124   // conversion here, which depends on whether the input or output has
125   // more elements.
126   bool isLittleEndian = TD.isLittleEndian();
127   
128   SmallVector<Constant*, 32> Result;
129   if (NumDstElt < NumSrcElt) {
130     // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
131     Constant *Zero = Constant::getNullValue(DstEltTy);
132     unsigned Ratio = NumSrcElt/NumDstElt;
133     unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
134     unsigned SrcElt = 0;
135     for (unsigned i = 0; i != NumDstElt; ++i) {
136       // Build each element of the result.
137       Constant *Elt = Zero;
138       unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
139       for (unsigned j = 0; j != Ratio; ++j) {
140         Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
141         if (!Src)  // Reject constantexpr elements.
142           return ConstantExpr::getBitCast(C, DestTy);
143         
144         // Zero extend the element to the right size.
145         Src = ConstantExpr::getZExt(Src, Elt->getType());
146         
147         // Shift it to the right place, depending on endianness.
148         Src = ConstantExpr::getShl(Src, 
149                                    ConstantInt::get(Src->getType(), ShiftAmt));
150         ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
151         
152         // Mix it in.
153         Elt = ConstantExpr::getOr(Elt, Src);
154       }
155       Result.push_back(Elt);
156     }
157   } else {
158     // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
159     unsigned Ratio = NumDstElt/NumSrcElt;
160     unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
161     
162     // Loop over each source value, expanding into multiple results.
163     for (unsigned i = 0; i != NumSrcElt; ++i) {
164       Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
165       if (!Src)  // Reject constantexpr elements.
166         return ConstantExpr::getBitCast(C, DestTy);
167       
168       unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
169       for (unsigned j = 0; j != Ratio; ++j) {
170         // Shift the piece of the value into the right place, depending on
171         // endianness.
172         Constant *Elt = ConstantExpr::getLShr(Src, 
173                                     ConstantInt::get(Src->getType(), ShiftAmt));
174         ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
175         
176         // Truncate and remember this piece.
177         Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
178       }
179     }
180   }
181   
182   return ConstantVector::get(Result);
183 }
184
185
186 /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
187 /// from a global, return the global and the constant.  Because of
188 /// constantexprs, this function is recursive.
189 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
190                                        int64_t &Offset, const TargetData &TD) {
191   // Trivial case, constant is the global.
192   if ((GV = dyn_cast<GlobalValue>(C))) {
193     Offset = 0;
194     return true;
195   }
196   
197   // Otherwise, if this isn't a constant expr, bail out.
198   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
199   if (!CE) return false;
200   
201   // Look through ptr->int and ptr->ptr casts.
202   if (CE->getOpcode() == Instruction::PtrToInt ||
203       CE->getOpcode() == Instruction::BitCast)
204     return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
205   
206   // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)    
207   if (CE->getOpcode() == Instruction::GetElementPtr) {
208     // Cannot compute this if the element type of the pointer is missing size
209     // info.
210     if (!cast<PointerType>(CE->getOperand(0)->getType())
211                  ->getElementType()->isSized())
212       return false;
213     
214     // If the base isn't a global+constant, we aren't either.
215     if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
216       return false;
217     
218     // Otherwise, add any offset that our operands provide.
219     gep_type_iterator GTI = gep_type_begin(CE);
220     for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
221          i != e; ++i, ++GTI) {
222       ConstantInt *CI = dyn_cast<ConstantInt>(*i);
223       if (!CI) return false;  // Index isn't a simple constant?
224       if (CI->isZero()) continue;  // Not adding anything.
225       
226       if (StructType *ST = dyn_cast<StructType>(*GTI)) {
227         // N = N + Offset
228         Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
229       } else {
230         SequentialType *SQT = cast<SequentialType>(*GTI);
231         Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
232       }
233     }
234     return true;
235   }
236   
237   return false;
238 }
239
240 /// ReadDataFromGlobal - Recursive helper to read bits out of global.  C is the
241 /// constant being copied out of. ByteOffset is an offset into C.  CurPtr is the
242 /// pointer to copy results into and BytesLeft is the number of bytes left in
243 /// the CurPtr buffer.  TD is the target data.
244 static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
245                                unsigned char *CurPtr, unsigned BytesLeft,
246                                const TargetData &TD) {
247   assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
248          "Out of range access");
249   
250   // If this element is zero or undefined, we can just return since *CurPtr is
251   // zero initialized.
252   if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
253     return true;
254   
255   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
256     if (CI->getBitWidth() > 64 ||
257         (CI->getBitWidth() & 7) != 0)
258       return false;
259     
260     uint64_t Val = CI->getZExtValue();
261     unsigned IntBytes = unsigned(CI->getBitWidth()/8);
262     
263     for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
264       CurPtr[i] = (unsigned char)(Val >> (ByteOffset * 8));
265       ++ByteOffset;
266     }
267     return true;
268   }
269   
270   if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
271     if (CFP->getType()->isDoubleTy()) {
272       C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
273       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
274     }
275     if (CFP->getType()->isFloatTy()){
276       C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
277       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
278     }
279     return false;
280   }
281
282   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
283     const StructLayout *SL = TD.getStructLayout(CS->getType());
284     unsigned Index = SL->getElementContainingOffset(ByteOffset);
285     uint64_t CurEltOffset = SL->getElementOffset(Index);
286     ByteOffset -= CurEltOffset;
287     
288     while (1) {
289       // If the element access is to the element itself and not to tail padding,
290       // read the bytes from the element.
291       uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
292
293       if (ByteOffset < EltSize &&
294           !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
295                               BytesLeft, TD))
296         return false;
297       
298       ++Index;
299       
300       // Check to see if we read from the last struct element, if so we're done.
301       if (Index == CS->getType()->getNumElements())
302         return true;
303
304       // If we read all of the bytes we needed from this element we're done.
305       uint64_t NextEltOffset = SL->getElementOffset(Index);
306
307       if (BytesLeft <= NextEltOffset-CurEltOffset-ByteOffset)
308         return true;
309
310       // Move to the next element of the struct.
311       CurPtr += NextEltOffset-CurEltOffset-ByteOffset;
312       BytesLeft -= NextEltOffset-CurEltOffset-ByteOffset;
313       ByteOffset = 0;
314       CurEltOffset = NextEltOffset;
315     }
316     // not reached.
317   }
318
319   if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
320     uint64_t EltSize = TD.getTypeAllocSize(CA->getType()->getElementType());
321     uint64_t Index = ByteOffset / EltSize;
322     uint64_t Offset = ByteOffset - Index * EltSize;
323     for (; Index != CA->getType()->getNumElements(); ++Index) {
324       if (!ReadDataFromGlobal(CA->getOperand(Index), Offset, CurPtr,
325                               BytesLeft, TD))
326         return false;
327       if (EltSize >= BytesLeft)
328         return true;
329       
330       Offset = 0;
331       BytesLeft -= EltSize;
332       CurPtr += EltSize;
333     }
334     return true;
335   }
336   
337   if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
338     uint64_t EltSize = TD.getTypeAllocSize(CV->getType()->getElementType());
339     uint64_t Index = ByteOffset / EltSize;
340     uint64_t Offset = ByteOffset - Index * EltSize;
341     for (; Index != CV->getType()->getNumElements(); ++Index) {
342       if (!ReadDataFromGlobal(CV->getOperand(Index), Offset, CurPtr,
343                               BytesLeft, TD))
344         return false;
345       if (EltSize >= BytesLeft)
346         return true;
347       
348       Offset = 0;
349       BytesLeft -= EltSize;
350       CurPtr += EltSize;
351     }
352     return true;
353   }
354   
355   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
356     if (CE->getOpcode() == Instruction::IntToPtr &&
357         CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getContext())) 
358         return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr, 
359                                   BytesLeft, TD);
360   }
361
362   // Otherwise, unknown initializer type.
363   return false;
364 }
365
366 static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
367                                                  const TargetData &TD) {
368   Type *LoadTy = cast<PointerType>(C->getType())->getElementType();
369   IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
370   
371   // If this isn't an integer load we can't fold it directly.
372   if (!IntType) {
373     // If this is a float/double load, we can try folding it as an int32/64 load
374     // and then bitcast the result.  This can be useful for union cases.  Note
375     // that address spaces don't matter here since we're not going to result in
376     // an actual new load.
377     Type *MapTy;
378     if (LoadTy->isFloatTy())
379       MapTy = Type::getInt32PtrTy(C->getContext());
380     else if (LoadTy->isDoubleTy())
381       MapTy = Type::getInt64PtrTy(C->getContext());
382     else if (LoadTy->isVectorTy()) {
383       MapTy = IntegerType::get(C->getContext(),
384                                TD.getTypeAllocSizeInBits(LoadTy));
385       MapTy = PointerType::getUnqual(MapTy);
386     } else
387       return 0;
388
389     C = FoldBitCast(C, MapTy, TD);
390     if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
391       return FoldBitCast(Res, LoadTy, TD);
392     return 0;
393   }
394   
395   unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
396   if (BytesLoaded > 32 || BytesLoaded == 0) return 0;
397   
398   GlobalValue *GVal;
399   int64_t Offset;
400   if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
401     return 0;
402   
403   GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
404   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
405       !GV->getInitializer()->getType()->isSized())
406     return 0;
407
408   // If we're loading off the beginning of the global, some bytes may be valid,
409   // but we don't try to handle this.
410   if (Offset < 0) return 0;
411   
412   // If we're not accessing anything in this constant, the result is undefined.
413   if (uint64_t(Offset) >= TD.getTypeAllocSize(GV->getInitializer()->getType()))
414     return UndefValue::get(IntType);
415   
416   unsigned char RawBytes[32] = {0};
417   if (!ReadDataFromGlobal(GV->getInitializer(), Offset, RawBytes,
418                           BytesLoaded, TD))
419     return 0;
420
421   APInt ResultVal = APInt(IntType->getBitWidth(), RawBytes[BytesLoaded-1]);
422   for (unsigned i = 1; i != BytesLoaded; ++i) {
423     ResultVal <<= 8;
424     ResultVal |= RawBytes[BytesLoaded-1-i];
425   }
426
427   return ConstantInt::get(IntType->getContext(), ResultVal);
428 }
429
430 /// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
431 /// produce if it is constant and determinable.  If this is not determinable,
432 /// return null.
433 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
434                                              const TargetData *TD) {
435   // First, try the easy cases:
436   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
437     if (GV->isConstant() && GV->hasDefinitiveInitializer())
438       return GV->getInitializer();
439
440   // If the loaded value isn't a constant expr, we can't handle it.
441   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
442   if (!CE) return 0;
443   
444   if (CE->getOpcode() == Instruction::GetElementPtr) {
445     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
446       if (GV->isConstant() && GV->hasDefinitiveInitializer())
447         if (Constant *V = 
448              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
449           return V;
450   }
451   
452   // Instead of loading constant c string, use corresponding integer value
453   // directly if string length is small enough.
454   std::string Str;
455   if (TD && GetConstantStringInfo(CE, Str) && !Str.empty()) {
456     unsigned StrLen = Str.length();
457     Type *Ty = cast<PointerType>(CE->getType())->getElementType();
458     unsigned NumBits = Ty->getPrimitiveSizeInBits();
459     // Replace load with immediate integer if the result is an integer or fp
460     // value.
461     if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
462         (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
463       APInt StrVal(NumBits, 0);
464       APInt SingleChar(NumBits, 0);
465       if (TD->isLittleEndian()) {
466         for (signed i = StrLen-1; i >= 0; i--) {
467           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
468           StrVal = (StrVal << 8) | SingleChar;
469         }
470       } else {
471         for (unsigned i = 0; i < StrLen; i++) {
472           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
473           StrVal = (StrVal << 8) | SingleChar;
474         }
475         // Append NULL at the end.
476         SingleChar = 0;
477         StrVal = (StrVal << 8) | SingleChar;
478       }
479       
480       Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
481       if (Ty->isFloatingPointTy())
482         Res = ConstantExpr::getBitCast(Res, Ty);
483       return Res;
484     }
485   }
486   
487   // If this load comes from anywhere in a constant global, and if the global
488   // is all undef or zero, we know what it loads.
489   if (GlobalVariable *GV =
490         dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
491     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
492       Type *ResTy = cast<PointerType>(C->getType())->getElementType();
493       if (GV->getInitializer()->isNullValue())
494         return Constant::getNullValue(ResTy);
495       if (isa<UndefValue>(GV->getInitializer()))
496         return UndefValue::get(ResTy);
497     }
498   }
499   
500   // Try hard to fold loads from bitcasted strange and non-type-safe things.  We
501   // currently don't do any of this for big endian systems.  It can be
502   // generalized in the future if someone is interested.
503   if (TD && TD->isLittleEndian())
504     return FoldReinterpretLoadFromConstPtr(CE, *TD);
505   return 0;
506 }
507
508 static Constant *ConstantFoldLoadInst(const LoadInst *LI, const TargetData *TD){
509   if (LI->isVolatile()) return 0;
510   
511   if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
512     return ConstantFoldLoadFromConstPtr(C, TD);
513
514   return 0;
515 }
516
517 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
518 /// Attempt to symbolically evaluate the result of a binary operator merging
519 /// these together.  If target data info is available, it is provided as TD, 
520 /// otherwise TD is null.
521 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
522                                            Constant *Op1, const TargetData *TD){
523   // SROA
524   
525   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
526   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
527   // bits.
528   
529   
530   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
531   // constant.  This happens frequently when iterating over a global array.
532   if (Opc == Instruction::Sub && TD) {
533     GlobalValue *GV1, *GV2;
534     int64_t Offs1, Offs2;
535     
536     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
537       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
538           GV1 == GV2) {
539         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
540         return ConstantInt::get(Op0->getType(), Offs1-Offs2);
541       }
542   }
543     
544   return 0;
545 }
546
547 /// CastGEPIndices - If array indices are not pointer-sized integers,
548 /// explicitly cast them so that they aren't implicitly casted by the
549 /// getelementptr.
550 static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
551                                 Type *ResultTy,
552                                 const TargetData *TD) {
553   if (!TD) return 0;
554   Type *IntPtrTy = TD->getIntPtrType(ResultTy->getContext());
555
556   bool Any = false;
557   SmallVector<Constant*, 32> NewIdxs;
558   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
559     if ((i == 1 ||
560          !isa<StructType>(GetElementPtrInst::getIndexedType(Ops[0]->getType(),
561                                                         Ops.slice(1, i-1)))) &&
562         Ops[i]->getType() != IntPtrTy) {
563       Any = true;
564       NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
565                                                                       true,
566                                                                       IntPtrTy,
567                                                                       true),
568                                               Ops[i], IntPtrTy));
569     } else
570       NewIdxs.push_back(Ops[i]);
571   }
572   if (!Any) return 0;
573
574   Constant *C =
575     ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
576   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
577     if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
578       C = Folded;
579   return C;
580 }
581
582 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
583 /// constant expression, do so.
584 static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
585                                          Type *ResultTy,
586                                          const TargetData *TD) {
587   Constant *Ptr = Ops[0];
588   if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
589     return 0;
590   
591   Type *IntPtrTy = TD->getIntPtrType(Ptr->getContext());
592
593   // If this is a constant expr gep that is effectively computing an
594   // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
595   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
596     if (!isa<ConstantInt>(Ops[i])) {
597       
598       // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
599       // "inttoptr (sub (ptrtoint Ptr), V)"
600       if (Ops.size() == 2 &&
601           cast<PointerType>(ResultTy)->getElementType()->isIntegerTy(8)) {
602         ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
603         assert((CE == 0 || CE->getType() == IntPtrTy) &&
604                "CastGEPIndices didn't canonicalize index types!");
605         if (CE && CE->getOpcode() == Instruction::Sub &&
606             CE->getOperand(0)->isNullValue()) {
607           Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
608           Res = ConstantExpr::getSub(Res, CE->getOperand(1));
609           Res = ConstantExpr::getIntToPtr(Res, ResultTy);
610           if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
611             Res = ConstantFoldConstantExpression(ResCE, TD);
612           return Res;
613         }
614       }
615       return 0;
616     }
617   
618   unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
619   APInt Offset =
620     APInt(BitWidth, TD->getIndexedOffset(Ptr->getType(),
621                                          makeArrayRef((Value **)Ops.data() + 1,
622                                                       Ops.size() - 1)));
623   Ptr = cast<Constant>(Ptr->stripPointerCasts());
624
625   // If this is a GEP of a GEP, fold it all into a single GEP.
626   while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
627     SmallVector<Value *, 4> NestedOps(GEP->op_begin()+1, GEP->op_end());
628
629     // Do not try the incorporate the sub-GEP if some index is not a number.
630     bool AllConstantInt = true;
631     for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
632       if (!isa<ConstantInt>(NestedOps[i])) {
633         AllConstantInt = false;
634         break;
635       }
636     if (!AllConstantInt)
637       break;
638
639     Ptr = cast<Constant>(GEP->getOperand(0));
640     Offset += APInt(BitWidth,
641                     TD->getIndexedOffset(Ptr->getType(), NestedOps));
642     Ptr = cast<Constant>(Ptr->stripPointerCasts());
643   }
644
645   // If the base value for this address is a literal integer value, fold the
646   // getelementptr to the resulting integer value casted to the pointer type.
647   APInt BasePtr(BitWidth, 0);
648   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
649     if (CE->getOpcode() == Instruction::IntToPtr)
650       if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
651         BasePtr = Base->getValue().zextOrTrunc(BitWidth);
652   if (Ptr->isNullValue() || BasePtr != 0) {
653     Constant *C = ConstantInt::get(Ptr->getContext(), Offset+BasePtr);
654     return ConstantExpr::getIntToPtr(C, ResultTy);
655   }
656
657   // Otherwise form a regular getelementptr. Recompute the indices so that
658   // we eliminate over-indexing of the notional static type array bounds.
659   // This makes it easy to determine if the getelementptr is "inbounds".
660   // Also, this helps GlobalOpt do SROA on GlobalVariables.
661   Type *Ty = Ptr->getType();
662   SmallVector<Constant*, 32> NewIdxs;
663   do {
664     if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
665       if (ATy->isPointerTy()) {
666         // The only pointer indexing we'll do is on the first index of the GEP.
667         if (!NewIdxs.empty())
668           break;
669        
670         // Only handle pointers to sized types, not pointers to functions.
671         if (!ATy->getElementType()->isSized())
672           return 0;
673       }
674         
675       // Determine which element of the array the offset points into.
676       APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
677       IntegerType *IntPtrTy = TD->getIntPtrType(Ty->getContext());
678       if (ElemSize == 0)
679         // The element size is 0. This may be [0 x Ty]*, so just use a zero
680         // index for this level and proceed to the next level to see if it can
681         // accommodate the offset.
682         NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
683       else {
684         // The element size is non-zero divide the offset by the element
685         // size (rounding down), to compute the index at this level.
686         APInt NewIdx = Offset.udiv(ElemSize);
687         Offset -= NewIdx * ElemSize;
688         NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
689       }
690       Ty = ATy->getElementType();
691     } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
692       // Determine which field of the struct the offset points into. The
693       // getZExtValue is at least as safe as the StructLayout API because we
694       // know the offset is within the struct at this point.
695       const StructLayout &SL = *TD->getStructLayout(STy);
696       unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
697       NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
698                                          ElIdx));
699       Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
700       Ty = STy->getTypeAtIndex(ElIdx);
701     } else {
702       // We've reached some non-indexable type.
703       break;
704     }
705   } while (Ty != cast<PointerType>(ResultTy)->getElementType());
706
707   // If we haven't used up the entire offset by descending the static
708   // type, then the offset is pointing into the middle of an indivisible
709   // member, so we can't simplify it.
710   if (Offset != 0)
711     return 0;
712
713   // Create a GEP.
714   Constant *C =
715     ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
716   assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
717          "Computed GetElementPtr has unexpected type!");
718
719   // If we ended up indexing a member with a type that doesn't match
720   // the type of what the original indices indexed, add a cast.
721   if (Ty != cast<PointerType>(ResultTy)->getElementType())
722     C = FoldBitCast(C, ResultTy, *TD);
723
724   return C;
725 }
726
727
728
729 //===----------------------------------------------------------------------===//
730 // Constant Folding public APIs
731 //===----------------------------------------------------------------------===//
732
733 /// ConstantFoldInstruction - Try to constant fold the specified instruction.
734 /// If successful, the constant result is returned, if not, null is returned.
735 /// Note that this fails if not all of the operands are constant.  Otherwise,
736 /// this function can only fail when attempting to fold instructions like loads
737 /// and stores, which have no constant expression form.
738 Constant *llvm::ConstantFoldInstruction(Instruction *I, const TargetData *TD) {
739   // Handle PHI nodes quickly here...
740   if (PHINode *PN = dyn_cast<PHINode>(I)) {
741     Constant *CommonValue = 0;
742
743     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
744       Value *Incoming = PN->getIncomingValue(i);
745       // If the incoming value is undef then skip it.  Note that while we could
746       // skip the value if it is equal to the phi node itself we choose not to
747       // because that would break the rule that constant folding only applies if
748       // all operands are constants.
749       if (isa<UndefValue>(Incoming))
750         continue;
751       // If the incoming value is not a constant, or is a different constant to
752       // the one we saw previously, then give up.
753       Constant *C = dyn_cast<Constant>(Incoming);
754       if (!C || (CommonValue && C != CommonValue))
755         return 0;
756       CommonValue = C;
757     }
758
759     // If we reach here, all incoming values are the same constant or undef.
760     return CommonValue ? CommonValue : UndefValue::get(PN->getType());
761   }
762
763   // Scan the operand list, checking to see if they are all constants, if so,
764   // hand off to ConstantFoldInstOperands.
765   SmallVector<Constant*, 8> Ops;
766   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
767     if (Constant *Op = dyn_cast<Constant>(*i))
768       Ops.push_back(Op);
769     else
770       return 0;  // All operands not constant!
771
772   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
773     return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
774                                            TD);
775   
776   if (const LoadInst *LI = dyn_cast<LoadInst>(I))
777     return ConstantFoldLoadInst(LI, TD);
778
779   if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I))
780     return ConstantExpr::getInsertValue(
781                                 cast<Constant>(IVI->getAggregateOperand()),
782                                 cast<Constant>(IVI->getInsertedValueOperand()),
783                                 IVI->getIndices());
784
785   if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I))
786     return ConstantExpr::getExtractValue(
787                                     cast<Constant>(EVI->getAggregateOperand()),
788                                     EVI->getIndices());
789
790   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD);
791 }
792
793 /// ConstantFoldConstantExpression - Attempt to fold the constant expression
794 /// using the specified TargetData.  If successful, the constant result is
795 /// result is returned, if not, null is returned.
796 Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
797                                                const TargetData *TD) {
798   SmallVector<Constant*, 8> Ops;
799   for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end();
800        i != e; ++i) {
801     Constant *NewC = cast<Constant>(*i);
802     // Recursively fold the ConstantExpr's operands.
803     if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC))
804       NewC = ConstantFoldConstantExpression(NewCE, TD);
805     Ops.push_back(NewC);
806   }
807
808   if (CE->isCompare())
809     return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
810                                            TD);
811   return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD);
812 }
813
814 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
815 /// specified opcode and operands.  If successful, the constant result is
816 /// returned, if not, null is returned.  Note that this function can fail when
817 /// attempting to fold instructions like loads and stores, which have no
818 /// constant expression form.
819 ///
820 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
821 /// information, due to only being passed an opcode and operands. Constant
822 /// folding using this function strips this information.
823 ///
824 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy, 
825                                          ArrayRef<Constant *> Ops,
826                                          const TargetData *TD) {
827   // Handle easy binops first.
828   if (Instruction::isBinaryOp(Opcode)) {
829     if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
830       if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
831         return C;
832     
833     return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
834   }
835   
836   switch (Opcode) {
837   default: return 0;
838   case Instruction::ICmp:
839   case Instruction::FCmp: assert(0 && "Invalid for compares");
840   case Instruction::Call:
841     if (Function *F = dyn_cast<Function>(Ops.back()))
842       if (canConstantFoldCallTo(F))
843         return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1));
844     return 0;
845   case Instruction::PtrToInt:
846     // If the input is a inttoptr, eliminate the pair.  This requires knowing
847     // the width of a pointer, so it can't be done in ConstantExpr::getCast.
848     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
849       if (TD && CE->getOpcode() == Instruction::IntToPtr) {
850         Constant *Input = CE->getOperand(0);
851         unsigned InWidth = Input->getType()->getScalarSizeInBits();
852         if (TD->getPointerSizeInBits() < InWidth) {
853           Constant *Mask = 
854             ConstantInt::get(CE->getContext(), APInt::getLowBitsSet(InWidth,
855                                                   TD->getPointerSizeInBits()));
856           Input = ConstantExpr::getAnd(Input, Mask);
857         }
858         // Do a zext or trunc to get to the dest size.
859         return ConstantExpr::getIntegerCast(Input, DestTy, false);
860       }
861     }
862     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
863   case Instruction::IntToPtr:
864     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
865     // the int size is >= the ptr size.  This requires knowing the width of a
866     // pointer, so it can't be done in ConstantExpr::getCast.
867     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0]))
868       if (TD &&
869           TD->getPointerSizeInBits() <= CE->getType()->getScalarSizeInBits() &&
870           CE->getOpcode() == Instruction::PtrToInt)
871         return FoldBitCast(CE->getOperand(0), DestTy, *TD);
872
873     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
874   case Instruction::Trunc:
875   case Instruction::ZExt:
876   case Instruction::SExt:
877   case Instruction::FPTrunc:
878   case Instruction::FPExt:
879   case Instruction::UIToFP:
880   case Instruction::SIToFP:
881   case Instruction::FPToUI:
882   case Instruction::FPToSI:
883       return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
884   case Instruction::BitCast:
885     if (TD)
886       return FoldBitCast(Ops[0], DestTy, *TD);
887     return ConstantExpr::getBitCast(Ops[0], DestTy);
888   case Instruction::Select:
889     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
890   case Instruction::ExtractElement:
891     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
892   case Instruction::InsertElement:
893     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
894   case Instruction::ShuffleVector:
895     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
896   case Instruction::GetElementPtr:
897     if (Constant *C = CastGEPIndices(Ops, DestTy, TD))
898       return C;
899     if (Constant *C = SymbolicallyEvaluateGEP(Ops, DestTy, TD))
900       return C;
901     
902     return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
903   }
904 }
905
906 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
907 /// instruction (icmp/fcmp) with the specified operands.  If it fails, it
908 /// returns a constant expression of the specified operands.
909 ///
910 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
911                                                 Constant *Ops0, Constant *Ops1, 
912                                                 const TargetData *TD) {
913   // fold: icmp (inttoptr x), null         -> icmp x, 0
914   // fold: icmp (ptrtoint x), 0            -> icmp x, null
915   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
916   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
917   //
918   // ConstantExpr::getCompare cannot do this, because it doesn't have TD
919   // around to know if bit truncation is happening.
920   if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
921     if (TD && Ops1->isNullValue()) {
922       Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
923       if (CE0->getOpcode() == Instruction::IntToPtr) {
924         // Convert the integer value to the right size to ensure we get the
925         // proper extension or truncation.
926         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
927                                                    IntPtrTy, false);
928         Constant *Null = Constant::getNullValue(C->getType());
929         return ConstantFoldCompareInstOperands(Predicate, C, Null, TD);
930       }
931       
932       // Only do this transformation if the int is intptrty in size, otherwise
933       // there is a truncation or extension that we aren't modeling.
934       if (CE0->getOpcode() == Instruction::PtrToInt && 
935           CE0->getType() == IntPtrTy) {
936         Constant *C = CE0->getOperand(0);
937         Constant *Null = Constant::getNullValue(C->getType());
938         return ConstantFoldCompareInstOperands(Predicate, C, Null, TD);
939       }
940     }
941     
942     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
943       if (TD && CE0->getOpcode() == CE1->getOpcode()) {
944         Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
945
946         if (CE0->getOpcode() == Instruction::IntToPtr) {
947           // Convert the integer value to the right size to ensure we get the
948           // proper extension or truncation.
949           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
950                                                       IntPtrTy, false);
951           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
952                                                       IntPtrTy, false);
953           return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD);
954         }
955
956         // Only do this transformation if the int is intptrty in size, otherwise
957         // there is a truncation or extension that we aren't modeling.
958         if ((CE0->getOpcode() == Instruction::PtrToInt &&
959              CE0->getType() == IntPtrTy &&
960              CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()))
961           return ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0),
962                                                  CE1->getOperand(0), TD);
963       }
964     }
965     
966     // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
967     // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
968     if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
969         CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
970       Constant *LHS = 
971         ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,TD);
972       Constant *RHS = 
973         ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,TD);
974       unsigned OpC = 
975         Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
976       Constant *Ops[] = { LHS, RHS };
977       return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD);
978     }
979   }
980   
981   return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
982 }
983
984
985 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
986 /// getelementptr constantexpr, return the constant value being addressed by the
987 /// constant expression, or null if something is funny and we can't decide.
988 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, 
989                                                        ConstantExpr *CE) {
990   if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
991     return 0;  // Do not allow stepping over the value!
992   
993   // Loop over all of the operands, tracking down which value we are
994   // addressing...
995   gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
996   for (++I; I != E; ++I)
997     if (StructType *STy = dyn_cast<StructType>(*I)) {
998       ConstantInt *CU = cast<ConstantInt>(I.getOperand());
999       assert(CU->getZExtValue() < STy->getNumElements() &&
1000              "Struct index out of range!");
1001       unsigned El = (unsigned)CU->getZExtValue();
1002       if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
1003         C = CS->getOperand(El);
1004       } else if (isa<ConstantAggregateZero>(C)) {
1005         C = Constant::getNullValue(STy->getElementType(El));
1006       } else if (isa<UndefValue>(C)) {
1007         C = UndefValue::get(STy->getElementType(El));
1008       } else {
1009         return 0;
1010       }
1011     } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
1012       if (ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
1013         if (CI->getZExtValue() >= ATy->getNumElements())
1014          return 0;
1015         if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
1016           C = CA->getOperand(CI->getZExtValue());
1017         else if (isa<ConstantAggregateZero>(C))
1018           C = Constant::getNullValue(ATy->getElementType());
1019         else if (isa<UndefValue>(C))
1020           C = UndefValue::get(ATy->getElementType());
1021         else
1022           return 0;
1023       } else if (VectorType *VTy = dyn_cast<VectorType>(*I)) {
1024         if (CI->getZExtValue() >= VTy->getNumElements())
1025           return 0;
1026         if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
1027           C = CP->getOperand(CI->getZExtValue());
1028         else if (isa<ConstantAggregateZero>(C))
1029           C = Constant::getNullValue(VTy->getElementType());
1030         else if (isa<UndefValue>(C))
1031           C = UndefValue::get(VTy->getElementType());
1032         else
1033           return 0;
1034       } else {
1035         return 0;
1036       }
1037     } else {
1038       return 0;
1039     }
1040   return C;
1041 }
1042
1043
1044 //===----------------------------------------------------------------------===//
1045 //  Constant Folding for Calls
1046 //
1047
1048 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
1049 /// the specified function.
1050 bool
1051 llvm::canConstantFoldCallTo(const Function *F) {
1052   switch (F->getIntrinsicID()) {
1053   case Intrinsic::sqrt:
1054   case Intrinsic::powi:
1055   case Intrinsic::bswap:
1056   case Intrinsic::ctpop:
1057   case Intrinsic::ctlz:
1058   case Intrinsic::cttz:
1059   case Intrinsic::sadd_with_overflow:
1060   case Intrinsic::uadd_with_overflow:
1061   case Intrinsic::ssub_with_overflow:
1062   case Intrinsic::usub_with_overflow:
1063   case Intrinsic::smul_with_overflow:
1064   case Intrinsic::umul_with_overflow:
1065   case Intrinsic::convert_from_fp16:
1066   case Intrinsic::convert_to_fp16:
1067   case Intrinsic::x86_sse_cvtss2si:
1068   case Intrinsic::x86_sse_cvtss2si64:
1069   case Intrinsic::x86_sse_cvttss2si:
1070   case Intrinsic::x86_sse_cvttss2si64:
1071   case Intrinsic::x86_sse2_cvtsd2si:
1072   case Intrinsic::x86_sse2_cvtsd2si64:
1073   case Intrinsic::x86_sse2_cvttsd2si:
1074   case Intrinsic::x86_sse2_cvttsd2si64:
1075     return true;
1076   default:
1077     return false;
1078   case 0: break;
1079   }
1080
1081   if (!F->hasName()) return false;
1082   StringRef Name = F->getName();
1083   
1084   // In these cases, the check of the length is required.  We don't want to
1085   // return true for a name like "cos\0blah" which strcmp would return equal to
1086   // "cos", but has length 8.
1087   switch (Name[0]) {
1088   default: return false;
1089   case 'a':
1090     return Name == "acos" || Name == "asin" || 
1091       Name == "atan" || Name == "atan2";
1092   case 'c':
1093     return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
1094   case 'e':
1095     return Name == "exp" || Name == "exp2";
1096   case 'f':
1097     return Name == "fabs" || Name == "fmod" || Name == "floor";
1098   case 'l':
1099     return Name == "log" || Name == "log10";
1100   case 'p':
1101     return Name == "pow";
1102   case 's':
1103     return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1104       Name == "sinf" || Name == "sqrtf";
1105   case 't':
1106     return Name == "tan" || Name == "tanh";
1107   }
1108 }
1109
1110 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V, 
1111                                 Type *Ty) {
1112   sys::llvm_fenv_clearexcept();
1113   V = NativeFP(V);
1114   if (sys::llvm_fenv_testexcept()) {
1115     sys::llvm_fenv_clearexcept();
1116     return 0;
1117   }
1118   
1119   if (Ty->isFloatTy())
1120     return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1121   if (Ty->isDoubleTy())
1122     return ConstantFP::get(Ty->getContext(), APFloat(V));
1123   llvm_unreachable("Can only constant fold float/double");
1124   return 0; // dummy return to suppress warning
1125 }
1126
1127 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1128                                       double V, double W, Type *Ty) {
1129   sys::llvm_fenv_clearexcept();
1130   V = NativeFP(V, W);
1131   if (sys::llvm_fenv_testexcept()) {
1132     sys::llvm_fenv_clearexcept();
1133     return 0;
1134   }
1135   
1136   if (Ty->isFloatTy())
1137     return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1138   if (Ty->isDoubleTy())
1139     return ConstantFP::get(Ty->getContext(), APFloat(V));
1140   llvm_unreachable("Can only constant fold float/double");
1141   return 0; // dummy return to suppress warning
1142 }
1143
1144 /// ConstantFoldConvertToInt - Attempt to an SSE floating point to integer
1145 /// conversion of a constant floating point. If roundTowardZero is false, the
1146 /// default IEEE rounding is used (toward nearest, ties to even). This matches
1147 /// the behavior of the non-truncating SSE instructions in the default rounding
1148 /// mode. The desired integer type Ty is used to select how many bits are
1149 /// available for the result. Returns null if the conversion cannot be
1150 /// performed, otherwise returns the Constant value resulting from the
1151 /// conversion.
1152 static Constant *ConstantFoldConvertToInt(ConstantFP *Op, bool roundTowardZero,
1153                                           Type *Ty) {
1154   assert(Op && "Called with NULL operand");
1155   APFloat Val(Op->getValueAPF());
1156
1157   // All of these conversion intrinsics form an integer of at most 64bits.
1158   unsigned ResultWidth = cast<IntegerType>(Ty)->getBitWidth();
1159   assert(ResultWidth <= 64 &&
1160          "Can only constant fold conversions to 64 and 32 bit ints");
1161
1162   uint64_t UIntVal;
1163   bool isExact = false;
1164   APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1165                                               : APFloat::rmNearestTiesToEven;
1166   APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1167                                                   /*isSigned=*/true, mode,
1168                                                   &isExact);
1169   if (status != APFloat::opOK && status != APFloat::opInexact)
1170     return 0;
1171   return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1172 }
1173
1174 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
1175 /// with the specified arguments, returning null if unsuccessful.
1176 Constant *
1177 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands) {
1178   if (!F->hasName()) return 0;
1179   StringRef Name = F->getName();
1180
1181   Type *Ty = F->getReturnType();
1182   if (Operands.size() == 1) {
1183     if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
1184       if (F->getIntrinsicID() == Intrinsic::convert_to_fp16) {
1185         APFloat Val(Op->getValueAPF());
1186
1187         bool lost = false;
1188         Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1189
1190         return ConstantInt::get(F->getContext(), Val.bitcastToAPInt());
1191       }
1192
1193       if (!Ty->isFloatTy() && !Ty->isDoubleTy())
1194         return 0;
1195
1196       /// We only fold functions with finite arguments. Folding NaN and inf is
1197       /// likely to be aborted with an exception anyway, and some host libms
1198       /// have known errors raising exceptions.
1199       if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1200         return 0;
1201
1202       /// Currently APFloat versions of these functions do not exist, so we use
1203       /// the host native double versions.  Float versions are not called
1204       /// directly but for all these it is true (float)(f((double)arg)) ==
1205       /// f(arg).  Long double not supported yet.
1206       double V = Ty->isFloatTy() ? (double)Op->getValueAPF().convertToFloat() :
1207                                      Op->getValueAPF().convertToDouble();
1208       switch (Name[0]) {
1209       case 'a':
1210         if (Name == "acos")
1211           return ConstantFoldFP(acos, V, Ty);
1212         else if (Name == "asin")
1213           return ConstantFoldFP(asin, V, Ty);
1214         else if (Name == "atan")
1215           return ConstantFoldFP(atan, V, Ty);
1216         break;
1217       case 'c':
1218         if (Name == "ceil")
1219           return ConstantFoldFP(ceil, V, Ty);
1220         else if (Name == "cos")
1221           return ConstantFoldFP(cos, V, Ty);
1222         else if (Name == "cosh")
1223           return ConstantFoldFP(cosh, V, Ty);
1224         else if (Name == "cosf")
1225           return ConstantFoldFP(cos, V, Ty);
1226         break;
1227       case 'e':
1228         if (Name == "exp")
1229           return ConstantFoldFP(exp, V, Ty);
1230   
1231         if (Name == "exp2") {
1232           // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1233           // C99 library.
1234           return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1235         }
1236         break;
1237       case 'f':
1238         if (Name == "fabs")
1239           return ConstantFoldFP(fabs, V, Ty);
1240         else if (Name == "floor")
1241           return ConstantFoldFP(floor, V, Ty);
1242         break;
1243       case 'l':
1244         if (Name == "log" && V > 0)
1245           return ConstantFoldFP(log, V, Ty);
1246         else if (Name == "log10" && V > 0)
1247           return ConstantFoldFP(log10, V, Ty);
1248         else if (F->getIntrinsicID() == Intrinsic::sqrt &&
1249                  (Ty->isFloatTy() || Ty->isDoubleTy())) {
1250           if (V >= -0.0)
1251             return ConstantFoldFP(sqrt, V, Ty);
1252           else // Undefined
1253             return Constant::getNullValue(Ty);
1254         }
1255         break;
1256       case 's':
1257         if (Name == "sin")
1258           return ConstantFoldFP(sin, V, Ty);
1259         else if (Name == "sinh")
1260           return ConstantFoldFP(sinh, V, Ty);
1261         else if (Name == "sqrt" && V >= 0)
1262           return ConstantFoldFP(sqrt, V, Ty);
1263         else if (Name == "sqrtf" && V >= 0)
1264           return ConstantFoldFP(sqrt, V, Ty);
1265         else if (Name == "sinf")
1266           return ConstantFoldFP(sin, V, Ty);
1267         break;
1268       case 't':
1269         if (Name == "tan")
1270           return ConstantFoldFP(tan, V, Ty);
1271         else if (Name == "tanh")
1272           return ConstantFoldFP(tanh, V, Ty);
1273         break;
1274       default:
1275         break;
1276       }
1277       return 0;
1278     }
1279
1280     if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
1281       switch (F->getIntrinsicID()) {
1282       case Intrinsic::bswap:
1283         return ConstantInt::get(F->getContext(), Op->getValue().byteSwap());
1284       case Intrinsic::ctpop:
1285         return ConstantInt::get(Ty, Op->getValue().countPopulation());
1286       case Intrinsic::cttz:
1287         return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
1288       case Intrinsic::ctlz:
1289         return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
1290       case Intrinsic::convert_from_fp16: {
1291         APFloat Val(Op->getValue());
1292
1293         bool lost = false;
1294         APFloat::opStatus status =
1295           Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
1296
1297         // Conversion is always precise.
1298         (void)status;
1299         assert(status == APFloat::opOK && !lost &&
1300                "Precision lost during fp16 constfolding");
1301
1302         return ConstantFP::get(F->getContext(), Val);
1303       }
1304       default:
1305         return 0;
1306       }
1307     }
1308
1309     if (ConstantVector *Op = dyn_cast<ConstantVector>(Operands[0])) {
1310       switch (F->getIntrinsicID()) {
1311       default: break;
1312       case Intrinsic::x86_sse_cvtss2si:
1313       case Intrinsic::x86_sse_cvtss2si64:
1314       case Intrinsic::x86_sse2_cvtsd2si:
1315       case Intrinsic::x86_sse2_cvtsd2si64:
1316         if (ConstantFP *FPOp = dyn_cast<ConstantFP>(Op->getOperand(0)))
1317           return ConstantFoldConvertToInt(FPOp, /*roundTowardZero=*/false, Ty);
1318       case Intrinsic::x86_sse_cvttss2si:
1319       case Intrinsic::x86_sse_cvttss2si64:
1320       case Intrinsic::x86_sse2_cvttsd2si:
1321       case Intrinsic::x86_sse2_cvttsd2si64:
1322         if (ConstantFP *FPOp = dyn_cast<ConstantFP>(Op->getOperand(0)))
1323           return ConstantFoldConvertToInt(FPOp, /*roundTowardZero=*/true, Ty);
1324       }
1325     }
1326
1327     if (isa<UndefValue>(Operands[0])) {
1328       if (F->getIntrinsicID() == Intrinsic::bswap)
1329         return Operands[0];
1330       return 0;
1331     }
1332
1333     return 0;
1334   }
1335
1336   if (Operands.size() == 2) {
1337     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1338       if (!Ty->isFloatTy() && !Ty->isDoubleTy())
1339         return 0;
1340       double Op1V = Ty->isFloatTy() ? 
1341                       (double)Op1->getValueAPF().convertToFloat() :
1342                       Op1->getValueAPF().convertToDouble();
1343       if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1344         if (Op2->getType() != Op1->getType())
1345           return 0;
1346         
1347         double Op2V = Ty->isFloatTy() ? 
1348                       (double)Op2->getValueAPF().convertToFloat():
1349                       Op2->getValueAPF().convertToDouble();
1350
1351         if (Name == "pow")
1352           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1353         if (Name == "fmod")
1354           return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1355         if (Name == "atan2")
1356           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1357       } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1358         if (F->getIntrinsicID() == Intrinsic::powi && Ty->isFloatTy())
1359           return ConstantFP::get(F->getContext(),
1360                                  APFloat((float)std::pow((float)Op1V,
1361                                                  (int)Op2C->getZExtValue())));
1362         if (F->getIntrinsicID() == Intrinsic::powi && Ty->isDoubleTy())
1363           return ConstantFP::get(F->getContext(),
1364                                  APFloat((double)std::pow((double)Op1V,
1365                                                    (int)Op2C->getZExtValue())));
1366       }
1367       return 0;
1368     }
1369     
1370     
1371     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1372       if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1373         switch (F->getIntrinsicID()) {
1374         default: break;
1375         case Intrinsic::sadd_with_overflow:
1376         case Intrinsic::uadd_with_overflow:
1377         case Intrinsic::ssub_with_overflow:
1378         case Intrinsic::usub_with_overflow:
1379         case Intrinsic::smul_with_overflow:
1380         case Intrinsic::umul_with_overflow: {
1381           APInt Res;
1382           bool Overflow;
1383           switch (F->getIntrinsicID()) {
1384           default: assert(0 && "Invalid case");
1385           case Intrinsic::sadd_with_overflow:
1386             Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1387             break;
1388           case Intrinsic::uadd_with_overflow:
1389             Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1390             break;
1391           case Intrinsic::ssub_with_overflow:
1392             Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1393             break;
1394           case Intrinsic::usub_with_overflow:
1395             Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1396             break;
1397           case Intrinsic::smul_with_overflow:
1398             Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1399             break;
1400           case Intrinsic::umul_with_overflow:
1401             Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1402             break;
1403           }
1404           Constant *Ops[] = {
1405             ConstantInt::get(F->getContext(), Res),
1406             ConstantInt::get(Type::getInt1Ty(F->getContext()), Overflow)
1407           };
1408           return ConstantStruct::get(cast<StructType>(F->getReturnType()), Ops);
1409         }
1410         }
1411       }
1412       
1413       return 0;
1414     }
1415     return 0;
1416   }
1417   return 0;
1418 }