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