Subtraction is not commutative. Fixes PR23212!
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineCalls.cpp
1 //===- InstCombineCalls.cpp -----------------------------------------------===//
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 implements the visitCall and visitInvoke functions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombineInternal.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/MemoryBuiltins.h"
17 #include "llvm/IR/CallSite.h"
18 #include "llvm/IR/Dominators.h"
19 #include "llvm/IR/PatternMatch.h"
20 #include "llvm/IR/Statepoint.h"
21 #include "llvm/Transforms/Utils/BuildLibCalls.h"
22 #include "llvm/Transforms/Utils/Local.h"
23 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
24 using namespace llvm;
25 using namespace PatternMatch;
26
27 #define DEBUG_TYPE "instcombine"
28
29 STATISTIC(NumSimplified, "Number of library calls simplified");
30
31 /// getPromotedType - Return the specified type promoted as it would be to pass
32 /// though a va_arg area.
33 static Type *getPromotedType(Type *Ty) {
34   if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
35     if (ITy->getBitWidth() < 32)
36       return Type::getInt32Ty(Ty->getContext());
37   }
38   return Ty;
39 }
40
41 /// reduceToSingleValueType - Given an aggregate type which ultimately holds a
42 /// single scalar element, like {{{type}}} or [1 x type], return type.
43 static Type *reduceToSingleValueType(Type *T) {
44   while (!T->isSingleValueType()) {
45     if (StructType *STy = dyn_cast<StructType>(T)) {
46       if (STy->getNumElements() == 1)
47         T = STy->getElementType(0);
48       else
49         break;
50     } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
51       if (ATy->getNumElements() == 1)
52         T = ATy->getElementType();
53       else
54         break;
55     } else
56       break;
57   }
58
59   return T;
60 }
61
62 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
63   unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, AC, DT);
64   unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, AC, DT);
65   unsigned MinAlign = std::min(DstAlign, SrcAlign);
66   unsigned CopyAlign = MI->getAlignment();
67
68   if (CopyAlign < MinAlign) {
69     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
70                                              MinAlign, false));
71     return MI;
72   }
73
74   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
75   // load/store.
76   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
77   if (!MemOpLength) return nullptr;
78
79   // Source and destination pointer types are always "i8*" for intrinsic.  See
80   // if the size is something we can handle with a single primitive load/store.
81   // A single load+store correctly handles overlapping memory in the memmove
82   // case.
83   uint64_t Size = MemOpLength->getLimitedValue();
84   assert(Size && "0-sized memory transferring should be removed already.");
85
86   if (Size > 8 || (Size&(Size-1)))
87     return nullptr;  // If not 1/2/4/8 bytes, exit.
88
89   // Use an integer load+store unless we can find something better.
90   unsigned SrcAddrSp =
91     cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
92   unsigned DstAddrSp =
93     cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
94
95   IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
96   Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
97   Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
98
99   // Memcpy forces the use of i8* for the source and destination.  That means
100   // that if you're using memcpy to move one double around, you'll get a cast
101   // from double* to i8*.  We'd much rather use a double load+store rather than
102   // an i64 load+store, here because this improves the odds that the source or
103   // dest address will be promotable.  See if we can find a better type than the
104   // integer datatype.
105   Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
106   MDNode *CopyMD = nullptr;
107   if (StrippedDest != MI->getArgOperand(0)) {
108     Type *SrcETy = cast<PointerType>(StrippedDest->getType())
109                                     ->getElementType();
110     if (SrcETy->isSized() && DL.getTypeStoreSize(SrcETy) == Size) {
111       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
112       // down through these levels if so.
113       SrcETy = reduceToSingleValueType(SrcETy);
114
115       if (SrcETy->isSingleValueType()) {
116         NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
117         NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
118
119         // If the memcpy has metadata describing the members, see if we can
120         // get the TBAA tag describing our copy.
121         if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
122           if (M->getNumOperands() == 3 && M->getOperand(0) &&
123               mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
124               mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
125               M->getOperand(1) &&
126               mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
127               mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
128                   Size &&
129               M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
130             CopyMD = cast<MDNode>(M->getOperand(2));
131         }
132       }
133     }
134   }
135
136   // If the memcpy/memmove provides better alignment info than we can
137   // infer, use it.
138   SrcAlign = std::max(SrcAlign, CopyAlign);
139   DstAlign = std::max(DstAlign, CopyAlign);
140
141   Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
142   Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
143   LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
144   L->setAlignment(SrcAlign);
145   if (CopyMD)
146     L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
147   StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
148   S->setAlignment(DstAlign);
149   if (CopyMD)
150     S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
151
152   // Set the size of the copy to 0, it will be deleted on the next iteration.
153   MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
154   return MI;
155 }
156
157 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
158   unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, AC, DT);
159   if (MI->getAlignment() < Alignment) {
160     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
161                                              Alignment, false));
162     return MI;
163   }
164
165   // Extract the length and alignment and fill if they are constant.
166   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
167   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
168   if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
169     return nullptr;
170   uint64_t Len = LenC->getLimitedValue();
171   Alignment = MI->getAlignment();
172   assert(Len && "0-sized memory setting should be removed already.");
173
174   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
175   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
176     Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
177
178     Value *Dest = MI->getDest();
179     unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
180     Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
181     Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
182
183     // Alignment 0 is identity for alignment 1 for memset, but not store.
184     if (Alignment == 0) Alignment = 1;
185
186     // Extract the fill value and store.
187     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
188     StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
189                                         MI->isVolatile());
190     S->setAlignment(Alignment);
191
192     // Set the size of the copy to 0, it will be deleted on the next iteration.
193     MI->setLength(Constant::getNullValue(LenC->getType()));
194     return MI;
195   }
196
197   return nullptr;
198 }
199
200 /// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
201 /// source vectors, unless a zero bit is set. If a zero bit is set,
202 /// then ignore that half of the mask and clear that half of the vector.
203 static Value *SimplifyX86vperm2(const IntrinsicInst &II,
204                                 InstCombiner::BuilderTy &Builder) {
205   if (auto CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
206     VectorType *VecTy = cast<VectorType>(II.getType());
207     ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
208
209     // The immediate permute control byte looks like this:
210     //    [1:0] - select 128 bits from sources for low half of destination
211     //    [2]   - ignore
212     //    [3]   - zero low half of destination
213     //    [5:4] - select 128 bits from sources for high half of destination
214     //    [6]   - ignore
215     //    [7]   - zero high half of destination
216
217     uint8_t Imm = CInt->getZExtValue();
218
219     bool LowHalfZero = Imm & 0x08;
220     bool HighHalfZero = Imm & 0x80;
221
222     // If both zero mask bits are set, this was just a weird way to
223     // generate a zero vector.
224     if (LowHalfZero && HighHalfZero)
225       return ZeroVector;
226
227     // If 0 or 1 zero mask bits are set, this is a simple shuffle.
228     unsigned NumElts = VecTy->getNumElements();
229     unsigned HalfSize = NumElts / 2;
230     SmallVector<int, 8> ShuffleMask(NumElts);
231
232     // The high bit of the selection field chooses the 1st or 2nd operand.
233     bool LowInputSelect = Imm & 0x02;
234     bool HighInputSelect = Imm & 0x20;
235     
236     // The low bit of the selection field chooses the low or high half
237     // of the selected operand.
238     bool LowHalfSelect = Imm & 0x01;
239     bool HighHalfSelect = Imm & 0x10;
240
241     // Determine which operand(s) are actually in use for this instruction.
242     Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
243     Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
244     
245     // If needed, replace operands based on zero mask.
246     V0 = LowHalfZero ? ZeroVector : V0;
247     V1 = HighHalfZero ? ZeroVector : V1;
248     
249     // Permute low half of result.
250     unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
251     for (unsigned i = 0; i < HalfSize; ++i)
252       ShuffleMask[i] = StartIndex + i;
253
254     // Permute high half of result.
255     StartIndex = HighHalfSelect ? HalfSize : 0;
256     StartIndex += NumElts;
257     for (unsigned i = 0; i < HalfSize; ++i)
258       ShuffleMask[i + HalfSize] = StartIndex + i;
259
260     return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
261   }
262   return nullptr;
263 }
264
265 /// visitCallInst - CallInst simplification.  This mostly only handles folding
266 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
267 /// the heavy lifting.
268 ///
269 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
270   if (isFreeCall(&CI, TLI))
271     return visitFree(CI);
272
273   // If the caller function is nounwind, mark the call as nounwind, even if the
274   // callee isn't.
275   if (CI.getParent()->getParent()->doesNotThrow() &&
276       !CI.doesNotThrow()) {
277     CI.setDoesNotThrow();
278     return &CI;
279   }
280
281   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
282   if (!II) return visitCallSite(&CI);
283
284   // Intrinsics cannot occur in an invoke, so handle them here instead of in
285   // visitCallSite.
286   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
287     bool Changed = false;
288
289     // memmove/cpy/set of zero bytes is a noop.
290     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
291       if (NumBytes->isNullValue())
292         return EraseInstFromFunction(CI);
293
294       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
295         if (CI->getZExtValue() == 1) {
296           // Replace the instruction with just byte operations.  We would
297           // transform other cases to loads/stores, but we don't know if
298           // alignment is sufficient.
299         }
300     }
301
302     // No other transformations apply to volatile transfers.
303     if (MI->isVolatile())
304       return nullptr;
305
306     // If we have a memmove and the source operation is a constant global,
307     // then the source and dest pointers can't alias, so we can change this
308     // into a call to memcpy.
309     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
310       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
311         if (GVSrc->isConstant()) {
312           Module *M = CI.getParent()->getParent()->getParent();
313           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
314           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
315                            CI.getArgOperand(1)->getType(),
316                            CI.getArgOperand(2)->getType() };
317           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
318           Changed = true;
319         }
320     }
321
322     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
323       // memmove(x,x,size) -> noop.
324       if (MTI->getSource() == MTI->getDest())
325         return EraseInstFromFunction(CI);
326     }
327
328     // If we can determine a pointer alignment that is bigger than currently
329     // set, update the alignment.
330     if (isa<MemTransferInst>(MI)) {
331       if (Instruction *I = SimplifyMemTransfer(MI))
332         return I;
333     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
334       if (Instruction *I = SimplifyMemSet(MSI))
335         return I;
336     }
337
338     if (Changed) return II;
339   }
340
341   switch (II->getIntrinsicID()) {
342   default: break;
343   case Intrinsic::objectsize: {
344     uint64_t Size;
345     if (getObjectSize(II->getArgOperand(0), Size, DL, TLI))
346       return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size));
347     return nullptr;
348   }
349   case Intrinsic::bswap: {
350     Value *IIOperand = II->getArgOperand(0);
351     Value *X = nullptr;
352
353     // bswap(bswap(x)) -> x
354     if (match(IIOperand, m_BSwap(m_Value(X))))
355         return ReplaceInstUsesWith(CI, X);
356
357     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
358     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
359       unsigned C = X->getType()->getPrimitiveSizeInBits() -
360         IIOperand->getType()->getPrimitiveSizeInBits();
361       Value *CV = ConstantInt::get(X->getType(), C);
362       Value *V = Builder->CreateLShr(X, CV);
363       return new TruncInst(V, IIOperand->getType());
364     }
365     break;
366   }
367
368   case Intrinsic::powi:
369     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
370       // powi(x, 0) -> 1.0
371       if (Power->isZero())
372         return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
373       // powi(x, 1) -> x
374       if (Power->isOne())
375         return ReplaceInstUsesWith(CI, II->getArgOperand(0));
376       // powi(x, -1) -> 1/x
377       if (Power->isAllOnesValue())
378         return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
379                                           II->getArgOperand(0));
380     }
381     break;
382   case Intrinsic::cttz: {
383     // If all bits below the first known one are known zero,
384     // this value is constant.
385     IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
386     // FIXME: Try to simplify vectors of integers.
387     if (!IT) break;
388     uint32_t BitWidth = IT->getBitWidth();
389     APInt KnownZero(BitWidth, 0);
390     APInt KnownOne(BitWidth, 0);
391     computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II);
392     unsigned TrailingZeros = KnownOne.countTrailingZeros();
393     APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
394     if ((Mask & KnownZero) == Mask)
395       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
396                                  APInt(BitWidth, TrailingZeros)));
397
398     }
399     break;
400   case Intrinsic::ctlz: {
401     // If all bits above the first known one are known zero,
402     // this value is constant.
403     IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
404     // FIXME: Try to simplify vectors of integers.
405     if (!IT) break;
406     uint32_t BitWidth = IT->getBitWidth();
407     APInt KnownZero(BitWidth, 0);
408     APInt KnownOne(BitWidth, 0);
409     computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II);
410     unsigned LeadingZeros = KnownOne.countLeadingZeros();
411     APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
412     if ((Mask & KnownZero) == Mask)
413       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
414                                  APInt(BitWidth, LeadingZeros)));
415
416     }
417     break;
418
419   case Intrinsic::uadd_with_overflow:
420   case Intrinsic::sadd_with_overflow:
421   case Intrinsic::umul_with_overflow:
422   case Intrinsic::smul_with_overflow:
423     if (isa<Constant>(II->getArgOperand(0)) &&
424         !isa<Constant>(II->getArgOperand(1))) {
425       // Canonicalize constants into the RHS.
426       Value *LHS = II->getArgOperand(0);
427       II->setArgOperand(0, II->getArgOperand(1));
428       II->setArgOperand(1, LHS);
429       return II;
430     }
431     [[clang::fallthrough]];
432
433   case Intrinsic::usub_with_overflow:
434   case Intrinsic::ssub_with_overflow: {
435     OverflowCheckFlavor OCF =
436         IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
437     assert(OCF != OCF_INVALID && "unexpected!");
438
439     Value *OperationResult = nullptr;
440     Constant *OverflowResult = nullptr;
441     if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
442                               *II, OperationResult, OverflowResult))
443       return CreateOverflowTuple(II, OperationResult, OverflowResult);
444
445     break;
446   }
447
448   case Intrinsic::minnum:
449   case Intrinsic::maxnum: {
450     Value *Arg0 = II->getArgOperand(0);
451     Value *Arg1 = II->getArgOperand(1);
452
453     // fmin(x, x) -> x
454     if (Arg0 == Arg1)
455       return ReplaceInstUsesWith(CI, Arg0);
456
457     const ConstantFP *C0 = dyn_cast<ConstantFP>(Arg0);
458     const ConstantFP *C1 = dyn_cast<ConstantFP>(Arg1);
459
460     // Canonicalize constants into the RHS.
461     if (C0 && !C1) {
462       II->setArgOperand(0, Arg1);
463       II->setArgOperand(1, Arg0);
464       return II;
465     }
466
467     // fmin(x, nan) -> x
468     if (C1 && C1->isNaN())
469       return ReplaceInstUsesWith(CI, Arg0);
470
471     // This is the value because if undef were NaN, we would return the other
472     // value and cannot return a NaN unless both operands are.
473     //
474     // fmin(undef, x) -> x
475     if (isa<UndefValue>(Arg0))
476       return ReplaceInstUsesWith(CI, Arg1);
477
478     // fmin(x, undef) -> x
479     if (isa<UndefValue>(Arg1))
480       return ReplaceInstUsesWith(CI, Arg0);
481
482     Value *X = nullptr;
483     Value *Y = nullptr;
484     if (II->getIntrinsicID() == Intrinsic::minnum) {
485       // fmin(x, fmin(x, y)) -> fmin(x, y)
486       // fmin(y, fmin(x, y)) -> fmin(x, y)
487       if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
488         if (Arg0 == X || Arg0 == Y)
489           return ReplaceInstUsesWith(CI, Arg1);
490       }
491
492       // fmin(fmin(x, y), x) -> fmin(x, y)
493       // fmin(fmin(x, y), y) -> fmin(x, y)
494       if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
495         if (Arg1 == X || Arg1 == Y)
496           return ReplaceInstUsesWith(CI, Arg0);
497       }
498
499       // TODO: fmin(nnan x, inf) -> x
500       // TODO: fmin(nnan ninf x, flt_max) -> x
501       if (C1 && C1->isInfinity()) {
502         // fmin(x, -inf) -> -inf
503         if (C1->isNegative())
504           return ReplaceInstUsesWith(CI, Arg1);
505       }
506     } else {
507       assert(II->getIntrinsicID() == Intrinsic::maxnum);
508       // fmax(x, fmax(x, y)) -> fmax(x, y)
509       // fmax(y, fmax(x, y)) -> fmax(x, y)
510       if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
511         if (Arg0 == X || Arg0 == Y)
512           return ReplaceInstUsesWith(CI, Arg1);
513       }
514
515       // fmax(fmax(x, y), x) -> fmax(x, y)
516       // fmax(fmax(x, y), y) -> fmax(x, y)
517       if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
518         if (Arg1 == X || Arg1 == Y)
519           return ReplaceInstUsesWith(CI, Arg0);
520       }
521
522       // TODO: fmax(nnan x, -inf) -> x
523       // TODO: fmax(nnan ninf x, -flt_max) -> x
524       if (C1 && C1->isInfinity()) {
525         // fmax(x, inf) -> inf
526         if (!C1->isNegative())
527           return ReplaceInstUsesWith(CI, Arg1);
528       }
529     }
530     break;
531   }
532   case Intrinsic::ppc_altivec_lvx:
533   case Intrinsic::ppc_altivec_lvxl:
534     // Turn PPC lvx -> load if the pointer is known aligned.
535     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >=
536         16) {
537       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
538                                          PointerType::getUnqual(II->getType()));
539       return new LoadInst(Ptr);
540     }
541     break;
542   case Intrinsic::ppc_vsx_lxvw4x:
543   case Intrinsic::ppc_vsx_lxvd2x: {
544     // Turn PPC VSX loads into normal loads.
545     Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
546                                         PointerType::getUnqual(II->getType()));
547     return new LoadInst(Ptr, Twine(""), false, 1);
548   }
549   case Intrinsic::ppc_altivec_stvx:
550   case Intrinsic::ppc_altivec_stvxl:
551     // Turn stvx -> store if the pointer is known aligned.
552     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, AC, DT) >=
553         16) {
554       Type *OpPtrTy =
555         PointerType::getUnqual(II->getArgOperand(0)->getType());
556       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
557       return new StoreInst(II->getArgOperand(0), Ptr);
558     }
559     break;
560   case Intrinsic::ppc_vsx_stxvw4x:
561   case Intrinsic::ppc_vsx_stxvd2x: {
562     // Turn PPC VSX stores into normal stores.
563     Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
564     Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
565     return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
566   }
567   case Intrinsic::ppc_qpx_qvlfs:
568     // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
569     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >=
570         16) {
571       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
572                                          PointerType::getUnqual(II->getType()));
573       return new LoadInst(Ptr);
574     }
575     break;
576   case Intrinsic::ppc_qpx_qvlfd:
577     // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
578     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, AC, DT) >=
579         32) {
580       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
581                                          PointerType::getUnqual(II->getType()));
582       return new LoadInst(Ptr);
583     }
584     break;
585   case Intrinsic::ppc_qpx_qvstfs:
586     // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
587     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, AC, DT) >=
588         16) {
589       Type *OpPtrTy =
590         PointerType::getUnqual(II->getArgOperand(0)->getType());
591       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
592       return new StoreInst(II->getArgOperand(0), Ptr);
593     }
594     break;
595   case Intrinsic::ppc_qpx_qvstfd:
596     // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
597     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, AC, DT) >=
598         32) {
599       Type *OpPtrTy =
600         PointerType::getUnqual(II->getArgOperand(0)->getType());
601       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
602       return new StoreInst(II->getArgOperand(0), Ptr);
603     }
604     break;
605   case Intrinsic::x86_sse_storeu_ps:
606   case Intrinsic::x86_sse2_storeu_pd:
607   case Intrinsic::x86_sse2_storeu_dq:
608     // Turn X86 storeu -> store if the pointer is known aligned.
609     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >=
610         16) {
611       Type *OpPtrTy =
612         PointerType::getUnqual(II->getArgOperand(1)->getType());
613       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
614       return new StoreInst(II->getArgOperand(1), Ptr);
615     }
616     break;
617
618   case Intrinsic::x86_sse_cvtss2si:
619   case Intrinsic::x86_sse_cvtss2si64:
620   case Intrinsic::x86_sse_cvttss2si:
621   case Intrinsic::x86_sse_cvttss2si64:
622   case Intrinsic::x86_sse2_cvtsd2si:
623   case Intrinsic::x86_sse2_cvtsd2si64:
624   case Intrinsic::x86_sse2_cvttsd2si:
625   case Intrinsic::x86_sse2_cvttsd2si64: {
626     // These intrinsics only demand the 0th element of their input vectors. If
627     // we can simplify the input based on that, do so now.
628     unsigned VWidth =
629       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
630     APInt DemandedElts(VWidth, 1);
631     APInt UndefElts(VWidth, 0);
632     if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
633                                               DemandedElts, UndefElts)) {
634       II->setArgOperand(0, V);
635       return II;
636     }
637     break;
638   }
639
640   // Constant fold <A x Bi> << Ci.
641   // FIXME: We don't handle _dq because it's a shift of an i128, but is
642   // represented in the IR as <2 x i64>. A per element shift is wrong.
643   case Intrinsic::x86_sse2_psll_d:
644   case Intrinsic::x86_sse2_psll_q:
645   case Intrinsic::x86_sse2_psll_w:
646   case Intrinsic::x86_sse2_pslli_d:
647   case Intrinsic::x86_sse2_pslli_q:
648   case Intrinsic::x86_sse2_pslli_w:
649   case Intrinsic::x86_avx2_psll_d:
650   case Intrinsic::x86_avx2_psll_q:
651   case Intrinsic::x86_avx2_psll_w:
652   case Intrinsic::x86_avx2_pslli_d:
653   case Intrinsic::x86_avx2_pslli_q:
654   case Intrinsic::x86_avx2_pslli_w:
655   case Intrinsic::x86_sse2_psrl_d:
656   case Intrinsic::x86_sse2_psrl_q:
657   case Intrinsic::x86_sse2_psrl_w:
658   case Intrinsic::x86_sse2_psrli_d:
659   case Intrinsic::x86_sse2_psrli_q:
660   case Intrinsic::x86_sse2_psrli_w:
661   case Intrinsic::x86_avx2_psrl_d:
662   case Intrinsic::x86_avx2_psrl_q:
663   case Intrinsic::x86_avx2_psrl_w:
664   case Intrinsic::x86_avx2_psrli_d:
665   case Intrinsic::x86_avx2_psrli_q:
666   case Intrinsic::x86_avx2_psrli_w: {
667     // Simplify if count is constant. To 0 if >= BitWidth,
668     // otherwise to shl/lshr.
669     auto CDV = dyn_cast<ConstantDataVector>(II->getArgOperand(1));
670     auto CInt = dyn_cast<ConstantInt>(II->getArgOperand(1));
671     if (!CDV && !CInt)
672       break;
673     ConstantInt *Count;
674     if (CDV)
675       Count = cast<ConstantInt>(CDV->getElementAsConstant(0));
676     else
677       Count = CInt;
678
679     auto Vec = II->getArgOperand(0);
680     auto VT = cast<VectorType>(Vec->getType());
681     if (Count->getZExtValue() >
682         VT->getElementType()->getPrimitiveSizeInBits() - 1)
683       return ReplaceInstUsesWith(
684           CI, ConstantAggregateZero::get(Vec->getType()));
685
686     bool isPackedShiftLeft = true;
687     switch (II->getIntrinsicID()) {
688     default : break;
689     case Intrinsic::x86_sse2_psrl_d:
690     case Intrinsic::x86_sse2_psrl_q:
691     case Intrinsic::x86_sse2_psrl_w:
692     case Intrinsic::x86_sse2_psrli_d:
693     case Intrinsic::x86_sse2_psrli_q:
694     case Intrinsic::x86_sse2_psrli_w:
695     case Intrinsic::x86_avx2_psrl_d:
696     case Intrinsic::x86_avx2_psrl_q:
697     case Intrinsic::x86_avx2_psrl_w:
698     case Intrinsic::x86_avx2_psrli_d:
699     case Intrinsic::x86_avx2_psrli_q:
700     case Intrinsic::x86_avx2_psrli_w: isPackedShiftLeft = false; break;
701     }
702
703     unsigned VWidth = VT->getNumElements();
704     // Get a constant vector of the same type as the first operand.
705     auto VTCI = ConstantInt::get(VT->getElementType(), Count->getZExtValue());
706     if (isPackedShiftLeft)
707       return BinaryOperator::CreateShl(Vec,
708           Builder->CreateVectorSplat(VWidth, VTCI));
709
710     return BinaryOperator::CreateLShr(Vec,
711         Builder->CreateVectorSplat(VWidth, VTCI));
712   }
713
714   case Intrinsic::x86_sse41_pmovsxbw:
715   case Intrinsic::x86_sse41_pmovsxwd:
716   case Intrinsic::x86_sse41_pmovsxdq:
717   case Intrinsic::x86_sse41_pmovzxbw:
718   case Intrinsic::x86_sse41_pmovzxwd:
719   case Intrinsic::x86_sse41_pmovzxdq: {
720     // pmov{s|z}x ignores the upper half of their input vectors.
721     unsigned VWidth =
722       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
723     unsigned LowHalfElts = VWidth / 2;
724     APInt InputDemandedElts(APInt::getBitsSet(VWidth, 0, LowHalfElts));
725     APInt UndefElts(VWidth, 0);
726     if (Value *TmpV = SimplifyDemandedVectorElts(
727             II->getArgOperand(0), InputDemandedElts, UndefElts)) {
728       II->setArgOperand(0, TmpV);
729       return II;
730     }
731     break;
732   }
733
734   case Intrinsic::x86_sse4a_insertqi: {
735     // insertqi x, y, 64, 0 can just copy y's lower bits and leave the top
736     // ones undef
737     // TODO: eventually we should lower this intrinsic to IR
738     if (auto CIWidth = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
739       if (auto CIStart = dyn_cast<ConstantInt>(II->getArgOperand(3))) {
740         unsigned Index = CIStart->getZExtValue();
741         // From AMD documentation: "a value of zero in the field length is
742         // defined as length of 64".
743         unsigned Length = CIWidth->equalsInt(0) ? 64 : CIWidth->getZExtValue();
744
745         // From AMD documentation: "If the sum of the bit index + length field
746         // is greater than 64, the results are undefined".
747
748         // Note that both field index and field length are 8-bit quantities.
749         // Since variables 'Index' and 'Length' are unsigned values
750         // obtained from zero-extending field index and field length
751         // respectively, their sum should never wrap around.
752         if ((Index + Length) > 64)
753           return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
754
755         if (Length == 64 && Index == 0) {
756           Value *Vec = II->getArgOperand(1);
757           Value *Undef = UndefValue::get(Vec->getType());
758           const uint32_t Mask[] = { 0, 2 };
759           return ReplaceInstUsesWith(
760               CI,
761               Builder->CreateShuffleVector(
762                   Vec, Undef, ConstantDataVector::get(
763                                   II->getContext(), makeArrayRef(Mask))));
764
765         } else if (auto Source =
766                        dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
767           if (Source->hasOneUse() &&
768               Source->getArgOperand(1) == II->getArgOperand(1)) {
769             // If the source of the insert has only one use and it's another
770             // insert (and they're both inserting from the same vector), try to
771             // bundle both together.
772             auto CISourceWidth =
773                 dyn_cast<ConstantInt>(Source->getArgOperand(2));
774             auto CISourceStart =
775                 dyn_cast<ConstantInt>(Source->getArgOperand(3));
776             if (CISourceStart && CISourceWidth) {
777               unsigned Start = CIStart->getZExtValue();
778               unsigned Width = CIWidth->getZExtValue();
779               unsigned End = Start + Width;
780               unsigned SourceStart = CISourceStart->getZExtValue();
781               unsigned SourceWidth = CISourceWidth->getZExtValue();
782               unsigned SourceEnd = SourceStart + SourceWidth;
783               unsigned NewStart, NewWidth;
784               bool ShouldReplace = false;
785               if (Start <= SourceStart && SourceStart <= End) {
786                 NewStart = Start;
787                 NewWidth = std::max(End, SourceEnd) - NewStart;
788                 ShouldReplace = true;
789               } else if (SourceStart <= Start && Start <= SourceEnd) {
790                 NewStart = SourceStart;
791                 NewWidth = std::max(SourceEnd, End) - NewStart;
792                 ShouldReplace = true;
793               }
794
795               if (ShouldReplace) {
796                 Constant *ConstantWidth = ConstantInt::get(
797                     II->getArgOperand(2)->getType(), NewWidth, false);
798                 Constant *ConstantStart = ConstantInt::get(
799                     II->getArgOperand(3)->getType(), NewStart, false);
800                 Value *Args[4] = { Source->getArgOperand(0),
801                                    II->getArgOperand(1), ConstantWidth,
802                                    ConstantStart };
803                 Module *M = CI.getParent()->getParent()->getParent();
804                 Value *F =
805                     Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
806                 return ReplaceInstUsesWith(CI, Builder->CreateCall(F, Args));
807               }
808             }
809           }
810         }
811       }
812     }
813     break;
814   }
815
816   case Intrinsic::x86_sse41_pblendvb:
817   case Intrinsic::x86_sse41_blendvps:
818   case Intrinsic::x86_sse41_blendvpd:
819   case Intrinsic::x86_avx_blendv_ps_256:
820   case Intrinsic::x86_avx_blendv_pd_256:
821   case Intrinsic::x86_avx2_pblendvb: {
822     // Convert blendv* to vector selects if the mask is constant.
823     // This optimization is convoluted because the intrinsic is defined as
824     // getting a vector of floats or doubles for the ps and pd versions.
825     // FIXME: That should be changed.
826     Value *Mask = II->getArgOperand(2);
827     if (auto C = dyn_cast<ConstantDataVector>(Mask)) {
828       auto Tyi1 = Builder->getInt1Ty();
829       auto SelectorType = cast<VectorType>(Mask->getType());
830       auto EltTy = SelectorType->getElementType();
831       unsigned Size = SelectorType->getNumElements();
832       unsigned BitWidth =
833           EltTy->isFloatTy()
834               ? 32
835               : (EltTy->isDoubleTy() ? 64 : EltTy->getIntegerBitWidth());
836       assert((BitWidth == 64 || BitWidth == 32 || BitWidth == 8) &&
837              "Wrong arguments for variable blend intrinsic");
838       SmallVector<Constant *, 32> Selectors;
839       for (unsigned I = 0; I < Size; ++I) {
840         // The intrinsics only read the top bit
841         uint64_t Selector;
842         if (BitWidth == 8)
843           Selector = C->getElementAsInteger(I);
844         else
845           Selector = C->getElementAsAPFloat(I).bitcastToAPInt().getZExtValue();
846         Selectors.push_back(ConstantInt::get(Tyi1, Selector >> (BitWidth - 1)));
847       }
848       auto NewSelector = ConstantVector::get(Selectors);
849       return SelectInst::Create(NewSelector, II->getArgOperand(1),
850                                 II->getArgOperand(0), "blendv");
851     } else {
852       break;
853     }
854   }
855
856   case Intrinsic::x86_avx_vpermilvar_ps:
857   case Intrinsic::x86_avx_vpermilvar_ps_256:
858   case Intrinsic::x86_avx_vpermilvar_pd:
859   case Intrinsic::x86_avx_vpermilvar_pd_256: {
860     // Convert vpermil* to shufflevector if the mask is constant.
861     Value *V = II->getArgOperand(1);
862     unsigned Size = cast<VectorType>(V->getType())->getNumElements();
863     assert(Size == 8 || Size == 4 || Size == 2);
864     uint32_t Indexes[8];
865     if (auto C = dyn_cast<ConstantDataVector>(V)) {
866       // The intrinsics only read one or two bits, clear the rest.
867       for (unsigned I = 0; I < Size; ++I) {
868         uint32_t Index = C->getElementAsInteger(I) & 0x3;
869         if (II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd ||
870             II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256)
871           Index >>= 1;
872         Indexes[I] = Index;
873       }
874     } else if (isa<ConstantAggregateZero>(V)) {
875       for (unsigned I = 0; I < Size; ++I)
876         Indexes[I] = 0;
877     } else {
878       break;
879     }
880     // The _256 variants are a bit trickier since the mask bits always index
881     // into the corresponding 128 half. In order to convert to a generic
882     // shuffle, we have to make that explicit.
883     if (II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 ||
884         II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) {
885       for (unsigned I = Size / 2; I < Size; ++I)
886         Indexes[I] += Size / 2;
887     }
888     auto NewC =
889         ConstantDataVector::get(V->getContext(), makeArrayRef(Indexes, Size));
890     auto V1 = II->getArgOperand(0);
891     auto V2 = UndefValue::get(V1->getType());
892     auto Shuffle = Builder->CreateShuffleVector(V1, V2, NewC);
893     return ReplaceInstUsesWith(CI, Shuffle);
894   }
895
896   case Intrinsic::x86_avx_vperm2f128_pd_256:
897   case Intrinsic::x86_avx_vperm2f128_ps_256:
898   case Intrinsic::x86_avx_vperm2f128_si_256:
899   case Intrinsic::x86_avx2_vperm2i128:
900     if (Value *V = SimplifyX86vperm2(*II, *Builder))
901       return ReplaceInstUsesWith(*II, V);
902     break;
903
904   case Intrinsic::ppc_altivec_vperm:
905     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
906     // Note that ppc_altivec_vperm has a big-endian bias, so when creating
907     // a vectorshuffle for little endian, we must undo the transformation
908     // performed on vec_perm in altivec.h.  That is, we must complement
909     // the permutation mask with respect to 31 and reverse the order of
910     // V1 and V2.
911     if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
912       assert(Mask->getType()->getVectorNumElements() == 16 &&
913              "Bad type for intrinsic!");
914
915       // Check that all of the elements are integer constants or undefs.
916       bool AllEltsOk = true;
917       for (unsigned i = 0; i != 16; ++i) {
918         Constant *Elt = Mask->getAggregateElement(i);
919         if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
920           AllEltsOk = false;
921           break;
922         }
923       }
924
925       if (AllEltsOk) {
926         // Cast the input vectors to byte vectors.
927         Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
928                                             Mask->getType());
929         Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
930                                             Mask->getType());
931         Value *Result = UndefValue::get(Op0->getType());
932
933         // Only extract each element once.
934         Value *ExtractedElts[32];
935         memset(ExtractedElts, 0, sizeof(ExtractedElts));
936
937         for (unsigned i = 0; i != 16; ++i) {
938           if (isa<UndefValue>(Mask->getAggregateElement(i)))
939             continue;
940           unsigned Idx =
941             cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
942           Idx &= 31;  // Match the hardware behavior.
943           if (DL.isLittleEndian())
944             Idx = 31 - Idx;
945
946           if (!ExtractedElts[Idx]) {
947             Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
948             Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
949             ExtractedElts[Idx] =
950               Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
951                                             Builder->getInt32(Idx&15));
952           }
953
954           // Insert this value into the result vector.
955           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
956                                                 Builder->getInt32(i));
957         }
958         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
959       }
960     }
961     break;
962
963   case Intrinsic::arm_neon_vld1:
964   case Intrinsic::arm_neon_vld2:
965   case Intrinsic::arm_neon_vld3:
966   case Intrinsic::arm_neon_vld4:
967   case Intrinsic::arm_neon_vld2lane:
968   case Intrinsic::arm_neon_vld3lane:
969   case Intrinsic::arm_neon_vld4lane:
970   case Intrinsic::arm_neon_vst1:
971   case Intrinsic::arm_neon_vst2:
972   case Intrinsic::arm_neon_vst3:
973   case Intrinsic::arm_neon_vst4:
974   case Intrinsic::arm_neon_vst2lane:
975   case Intrinsic::arm_neon_vst3lane:
976   case Intrinsic::arm_neon_vst4lane: {
977     unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL, II, AC, DT);
978     unsigned AlignArg = II->getNumArgOperands() - 1;
979     ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
980     if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
981       II->setArgOperand(AlignArg,
982                         ConstantInt::get(Type::getInt32Ty(II->getContext()),
983                                          MemAlign, false));
984       return II;
985     }
986     break;
987   }
988
989   case Intrinsic::arm_neon_vmulls:
990   case Intrinsic::arm_neon_vmullu:
991   case Intrinsic::aarch64_neon_smull:
992   case Intrinsic::aarch64_neon_umull: {
993     Value *Arg0 = II->getArgOperand(0);
994     Value *Arg1 = II->getArgOperand(1);
995
996     // Handle mul by zero first:
997     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
998       return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
999     }
1000
1001     // Check for constant LHS & RHS - in this case we just simplify.
1002     bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
1003                  II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
1004     VectorType *NewVT = cast<VectorType>(II->getType());
1005     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
1006       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
1007         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
1008         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
1009
1010         return ReplaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
1011       }
1012
1013       // Couldn't simplify - canonicalize constant to the RHS.
1014       std::swap(Arg0, Arg1);
1015     }
1016
1017     // Handle mul by one:
1018     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
1019       if (ConstantInt *Splat =
1020               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
1021         if (Splat->isOne())
1022           return CastInst::CreateIntegerCast(Arg0, II->getType(),
1023                                              /*isSigned=*/!Zext);
1024
1025     break;
1026   }
1027
1028   case Intrinsic::AMDGPU_rcp: {
1029     if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
1030       const APFloat &ArgVal = C->getValueAPF();
1031       APFloat Val(ArgVal.getSemantics(), 1.0);
1032       APFloat::opStatus Status = Val.divide(ArgVal,
1033                                             APFloat::rmNearestTiesToEven);
1034       // Only do this if it was exact and therefore not dependent on the
1035       // rounding mode.
1036       if (Status == APFloat::opOK)
1037         return ReplaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
1038     }
1039
1040     break;
1041   }
1042   case Intrinsic::stackrestore: {
1043     // If the save is right next to the restore, remove the restore.  This can
1044     // happen when variable allocas are DCE'd.
1045     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
1046       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
1047         BasicBlock::iterator BI = SS;
1048         if (&*++BI == II)
1049           return EraseInstFromFunction(CI);
1050       }
1051     }
1052
1053     // Scan down this block to see if there is another stack restore in the
1054     // same block without an intervening call/alloca.
1055     BasicBlock::iterator BI = II;
1056     TerminatorInst *TI = II->getParent()->getTerminator();
1057     bool CannotRemove = false;
1058     for (++BI; &*BI != TI; ++BI) {
1059       if (isa<AllocaInst>(BI)) {
1060         CannotRemove = true;
1061         break;
1062       }
1063       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
1064         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
1065           // If there is a stackrestore below this one, remove this one.
1066           if (II->getIntrinsicID() == Intrinsic::stackrestore)
1067             return EraseInstFromFunction(CI);
1068           // Otherwise, ignore the intrinsic.
1069         } else {
1070           // If we found a non-intrinsic call, we can't remove the stack
1071           // restore.
1072           CannotRemove = true;
1073           break;
1074         }
1075       }
1076     }
1077
1078     // If the stack restore is in a return, resume, or unwind block and if there
1079     // are no allocas or calls between the restore and the return, nuke the
1080     // restore.
1081     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
1082       return EraseInstFromFunction(CI);
1083     break;
1084   }
1085   case Intrinsic::assume: {
1086     // Canonicalize assume(a && b) -> assume(a); assume(b);
1087     // Note: New assumption intrinsics created here are registered by
1088     // the InstCombineIRInserter object.
1089     Value *IIOperand = II->getArgOperand(0), *A, *B,
1090           *AssumeIntrinsic = II->getCalledValue();
1091     if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
1092       Builder->CreateCall(AssumeIntrinsic, A, II->getName());
1093       Builder->CreateCall(AssumeIntrinsic, B, II->getName());
1094       return EraseInstFromFunction(*II);
1095     }
1096     // assume(!(a || b)) -> assume(!a); assume(!b);
1097     if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
1098       Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
1099                           II->getName());
1100       Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
1101                           II->getName());
1102       return EraseInstFromFunction(*II);
1103     }
1104
1105     // assume( (load addr) != null ) -> add 'nonnull' metadata to load
1106     // (if assume is valid at the load)
1107     if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) {
1108       Value *LHS = ICmp->getOperand(0);
1109       Value *RHS = ICmp->getOperand(1);
1110       if (ICmpInst::ICMP_NE == ICmp->getPredicate() &&
1111           isa<LoadInst>(LHS) &&
1112           isa<Constant>(RHS) &&
1113           RHS->getType()->isPointerTy() &&
1114           cast<Constant>(RHS)->isNullValue()) {
1115         LoadInst* LI = cast<LoadInst>(LHS);
1116         if (isValidAssumeForContext(II, LI, DT)) {
1117           MDNode *MD = MDNode::get(II->getContext(), None);
1118           LI->setMetadata(LLVMContext::MD_nonnull, MD);
1119           return EraseInstFromFunction(*II);
1120         }
1121       }
1122       // TODO: apply nonnull return attributes to calls and invokes
1123       // TODO: apply range metadata for range check patterns?
1124     }
1125     // If there is a dominating assume with the same condition as this one,
1126     // then this one is redundant, and should be removed.
1127     APInt KnownZero(1, 0), KnownOne(1, 0);
1128     computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
1129     if (KnownOne.isAllOnesValue())
1130       return EraseInstFromFunction(*II);
1131
1132     break;
1133   }
1134   case Intrinsic::experimental_gc_relocate: {
1135     // Translate facts known about a pointer before relocating into
1136     // facts about the relocate value, while being careful to
1137     // preserve relocation semantics.
1138     GCRelocateOperands Operands(II);
1139     Value *DerivedPtr = Operands.derivedPtr();
1140
1141     // Remove the relocation if unused, note that this check is required
1142     // to prevent the cases below from looping forever.
1143     if (II->use_empty())
1144       return EraseInstFromFunction(*II);
1145
1146     // Undef is undef, even after relocation.
1147     // TODO: provide a hook for this in GCStrategy.  This is clearly legal for
1148     // most practical collectors, but there was discussion in the review thread
1149     // about whether it was legal for all possible collectors.
1150     if (isa<UndefValue>(DerivedPtr))
1151       return ReplaceInstUsesWith(*II, DerivedPtr);
1152
1153     // The relocation of null will be null for most any collector.
1154     // TODO: provide a hook for this in GCStrategy.  There might be some weird
1155     // collector this property does not hold for.
1156     if (isa<ConstantPointerNull>(DerivedPtr))
1157       return ReplaceInstUsesWith(*II, DerivedPtr);
1158
1159     // isKnownNonNull -> nonnull attribute
1160     if (isKnownNonNull(DerivedPtr))
1161       II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
1162
1163     // isDereferenceablePointer -> deref attribute
1164     if (DerivedPtr->isDereferenceablePointer(DL)) {
1165       if (Argument *A = dyn_cast<Argument>(DerivedPtr)) {
1166         uint64_t Bytes = A->getDereferenceableBytes();
1167         II->addDereferenceableAttr(AttributeSet::ReturnIndex, Bytes);
1168       }
1169     }
1170
1171     // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
1172     // Canonicalize on the type from the uses to the defs
1173
1174     // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
1175   }
1176   }
1177
1178   return visitCallSite(II);
1179 }
1180
1181 // InvokeInst simplification
1182 //
1183 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1184   return visitCallSite(&II);
1185 }
1186
1187 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
1188 /// passed through the varargs area, we can eliminate the use of the cast.
1189 static bool isSafeToEliminateVarargsCast(const CallSite CS,
1190                                          const DataLayout &DL,
1191                                          const CastInst *const CI,
1192                                          const int ix) {
1193   if (!CI->isLosslessCast())
1194     return false;
1195
1196   // If this is a GC intrinsic, avoid munging types.  We need types for
1197   // statepoint reconstruction in SelectionDAG.
1198   // TODO: This is probably something which should be expanded to all
1199   // intrinsics since the entire point of intrinsics is that
1200   // they are understandable by the optimizer.
1201   if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
1202     return false;
1203
1204   // The size of ByVal or InAlloca arguments is derived from the type, so we
1205   // can't change to a type with a different size.  If the size were
1206   // passed explicitly we could avoid this check.
1207   if (!CS.isByValOrInAllocaArgument(ix))
1208     return true;
1209
1210   Type* SrcTy =
1211             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
1212   Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
1213   if (!SrcTy->isSized() || !DstTy->isSized())
1214     return false;
1215   if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
1216     return false;
1217   return true;
1218 }
1219
1220 // Try to fold some different type of calls here.
1221 // Currently we're only working with the checking functions, memcpy_chk,
1222 // mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
1223 // strcat_chk and strncat_chk.
1224 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
1225   if (!CI->getCalledFunction()) return nullptr;
1226
1227   auto InstCombineRAUW = [this](Instruction *From, Value *With) {
1228     ReplaceInstUsesWith(*From, With);
1229   };
1230   LibCallSimplifier Simplifier(DL, TLI, InstCombineRAUW);
1231   if (Value *With = Simplifier.optimizeCall(CI)) {
1232     ++NumSimplified;
1233     return CI->use_empty() ? CI : ReplaceInstUsesWith(*CI, With);
1234   }
1235
1236   return nullptr;
1237 }
1238
1239 static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
1240   // Strip off at most one level of pointer casts, looking for an alloca.  This
1241   // is good enough in practice and simpler than handling any number of casts.
1242   Value *Underlying = TrampMem->stripPointerCasts();
1243   if (Underlying != TrampMem &&
1244       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
1245     return nullptr;
1246   if (!isa<AllocaInst>(Underlying))
1247     return nullptr;
1248
1249   IntrinsicInst *InitTrampoline = nullptr;
1250   for (User *U : TrampMem->users()) {
1251     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
1252     if (!II)
1253       return nullptr;
1254     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
1255       if (InitTrampoline)
1256         // More than one init_trampoline writes to this value.  Give up.
1257         return nullptr;
1258       InitTrampoline = II;
1259       continue;
1260     }
1261     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
1262       // Allow any number of calls to adjust.trampoline.
1263       continue;
1264     return nullptr;
1265   }
1266
1267   // No call to init.trampoline found.
1268   if (!InitTrampoline)
1269     return nullptr;
1270
1271   // Check that the alloca is being used in the expected way.
1272   if (InitTrampoline->getOperand(0) != TrampMem)
1273     return nullptr;
1274
1275   return InitTrampoline;
1276 }
1277
1278 static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
1279                                                Value *TrampMem) {
1280   // Visit all the previous instructions in the basic block, and try to find a
1281   // init.trampoline which has a direct path to the adjust.trampoline.
1282   for (BasicBlock::iterator I = AdjustTramp,
1283        E = AdjustTramp->getParent()->begin(); I != E; ) {
1284     Instruction *Inst = --I;
1285     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1286       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
1287           II->getOperand(0) == TrampMem)
1288         return II;
1289     if (Inst->mayWriteToMemory())
1290       return nullptr;
1291   }
1292   return nullptr;
1293 }
1294
1295 // Given a call to llvm.adjust.trampoline, find and return the corresponding
1296 // call to llvm.init.trampoline if the call to the trampoline can be optimized
1297 // to a direct call to a function.  Otherwise return NULL.
1298 //
1299 static IntrinsicInst *FindInitTrampoline(Value *Callee) {
1300   Callee = Callee->stripPointerCasts();
1301   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
1302   if (!AdjustTramp ||
1303       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
1304     return nullptr;
1305
1306   Value *TrampMem = AdjustTramp->getOperand(0);
1307
1308   if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
1309     return IT;
1310   if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
1311     return IT;
1312   return nullptr;
1313 }
1314
1315 // visitCallSite - Improvements for call and invoke instructions.
1316 //
1317 Instruction *InstCombiner::visitCallSite(CallSite CS) {
1318   if (isAllocLikeFn(CS.getInstruction(), TLI))
1319     return visitAllocSite(*CS.getInstruction());
1320
1321   bool Changed = false;
1322
1323   // If the callee is a pointer to a function, attempt to move any casts to the
1324   // arguments of the call/invoke.
1325   Value *Callee = CS.getCalledValue();
1326   if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
1327     return nullptr;
1328
1329   if (Function *CalleeF = dyn_cast<Function>(Callee))
1330     // If the call and callee calling conventions don't match, this call must
1331     // be unreachable, as the call is undefined.
1332     if (CalleeF->getCallingConv() != CS.getCallingConv() &&
1333         // Only do this for calls to a function with a body.  A prototype may
1334         // not actually end up matching the implementation's calling conv for a
1335         // variety of reasons (e.g. it may be written in assembly).
1336         !CalleeF->isDeclaration()) {
1337       Instruction *OldCall = CS.getInstruction();
1338       new StoreInst(ConstantInt::getTrue(Callee->getContext()),
1339                 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
1340                                   OldCall);
1341       // If OldCall does not return void then replaceAllUsesWith undef.
1342       // This allows ValueHandlers and custom metadata to adjust itself.
1343       if (!OldCall->getType()->isVoidTy())
1344         ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
1345       if (isa<CallInst>(OldCall))
1346         return EraseInstFromFunction(*OldCall);
1347
1348       // We cannot remove an invoke, because it would change the CFG, just
1349       // change the callee to a null pointer.
1350       cast<InvokeInst>(OldCall)->setCalledFunction(
1351                                     Constant::getNullValue(CalleeF->getType()));
1352       return nullptr;
1353     }
1354
1355   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1356     // If CS does not return void then replaceAllUsesWith undef.
1357     // This allows ValueHandlers and custom metadata to adjust itself.
1358     if (!CS.getInstruction()->getType()->isVoidTy())
1359       ReplaceInstUsesWith(*CS.getInstruction(),
1360                           UndefValue::get(CS.getInstruction()->getType()));
1361
1362     if (isa<InvokeInst>(CS.getInstruction())) {
1363       // Can't remove an invoke because we cannot change the CFG.
1364       return nullptr;
1365     }
1366
1367     // This instruction is not reachable, just remove it.  We insert a store to
1368     // undef so that we know that this code is not reachable, despite the fact
1369     // that we can't modify the CFG here.
1370     new StoreInst(ConstantInt::getTrue(Callee->getContext()),
1371                   UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
1372                   CS.getInstruction());
1373
1374     return EraseInstFromFunction(*CS.getInstruction());
1375   }
1376
1377   if (IntrinsicInst *II = FindInitTrampoline(Callee))
1378     return transformCallThroughTrampoline(CS, II);
1379
1380   PointerType *PTy = cast<PointerType>(Callee->getType());
1381   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1382   if (FTy->isVarArg()) {
1383     int ix = FTy->getNumParams();
1384     // See if we can optimize any arguments passed through the varargs area of
1385     // the call.
1386     for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
1387            E = CS.arg_end(); I != E; ++I, ++ix) {
1388       CastInst *CI = dyn_cast<CastInst>(*I);
1389       if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
1390         *I = CI->getOperand(0);
1391         Changed = true;
1392       }
1393     }
1394   }
1395
1396   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
1397     // Inline asm calls cannot throw - mark them 'nounwind'.
1398     CS.setDoesNotThrow();
1399     Changed = true;
1400   }
1401
1402   // Try to optimize the call if possible, we require DataLayout for most of
1403   // this.  None of these calls are seen as possibly dead so go ahead and
1404   // delete the instruction now.
1405   if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1406     Instruction *I = tryOptimizeCall(CI);
1407     // If we changed something return the result, etc. Otherwise let
1408     // the fallthrough check.
1409     if (I) return EraseInstFromFunction(*I);
1410   }
1411
1412   return Changed ? CS.getInstruction() : nullptr;
1413 }
1414
1415 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
1416 // attempt to move the cast to the arguments of the call/invoke.
1417 //
1418 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1419   Function *Callee =
1420     dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
1421   if (!Callee)
1422     return false;
1423   // The prototype of thunks are a lie, don't try to directly call such
1424   // functions.
1425   if (Callee->hasFnAttribute("thunk"))
1426     return false;
1427   Instruction *Caller = CS.getInstruction();
1428   const AttributeSet &CallerPAL = CS.getAttributes();
1429
1430   // Okay, this is a cast from a function to a different type.  Unless doing so
1431   // would cause a type conversion of one of our arguments, change this call to
1432   // be a direct call with arguments casted to the appropriate types.
1433   //
1434   FunctionType *FT = Callee->getFunctionType();
1435   Type *OldRetTy = Caller->getType();
1436   Type *NewRetTy = FT->getReturnType();
1437
1438   // Check to see if we are changing the return type...
1439   if (OldRetTy != NewRetTy) {
1440
1441     if (NewRetTy->isStructTy())
1442       return false; // TODO: Handle multiple return values.
1443
1444     if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
1445       if (Callee->isDeclaration())
1446         return false;   // Cannot transform this return value.
1447
1448       if (!Caller->use_empty() &&
1449           // void -> non-void is handled specially
1450           !NewRetTy->isVoidTy())
1451         return false;   // Cannot transform this return value.
1452     }
1453
1454     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
1455       AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
1456       if (RAttrs.
1457           hasAttributes(AttributeFuncs::
1458                         typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
1459                         AttributeSet::ReturnIndex))
1460         return false;   // Attribute not compatible with transformed value.
1461     }
1462
1463     // If the callsite is an invoke instruction, and the return value is used by
1464     // a PHI node in a successor, we cannot change the return type of the call
1465     // because there is no place to put the cast instruction (without breaking
1466     // the critical edge).  Bail out in this case.
1467     if (!Caller->use_empty())
1468       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
1469         for (User *U : II->users())
1470           if (PHINode *PN = dyn_cast<PHINode>(U))
1471             if (PN->getParent() == II->getNormalDest() ||
1472                 PN->getParent() == II->getUnwindDest())
1473               return false;
1474   }
1475
1476   unsigned NumActualArgs = CS.arg_size();
1477   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1478
1479   // Prevent us turning:
1480   // declare void @takes_i32_inalloca(i32* inalloca)
1481   //  call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
1482   //
1483   // into:
1484   //  call void @takes_i32_inalloca(i32* null)
1485   //
1486   //  Similarly, avoid folding away bitcasts of byval calls.
1487   if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
1488       Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
1489     return false;
1490
1491   CallSite::arg_iterator AI = CS.arg_begin();
1492   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1493     Type *ParamTy = FT->getParamType(i);
1494     Type *ActTy = (*AI)->getType();
1495
1496     if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
1497       return false;   // Cannot transform this parameter value.
1498
1499     if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
1500           hasAttributes(AttributeFuncs::
1501                         typeIncompatible(ParamTy, i + 1), i + 1))
1502       return false;   // Attribute not compatible with transformed value.
1503
1504     if (CS.isInAllocaArgument(i))
1505       return false;   // Cannot transform to and from inalloca.
1506
1507     // If the parameter is passed as a byval argument, then we have to have a
1508     // sized type and the sized type has to have the same size as the old type.
1509     if (ParamTy != ActTy &&
1510         CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
1511                                                          Attribute::ByVal)) {
1512       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
1513       if (!ParamPTy || !ParamPTy->getElementType()->isSized())
1514         return false;
1515
1516       Type *CurElTy = ActTy->getPointerElementType();
1517       if (DL.getTypeAllocSize(CurElTy) !=
1518           DL.getTypeAllocSize(ParamPTy->getElementType()))
1519         return false;
1520     }
1521   }
1522
1523   if (Callee->isDeclaration()) {
1524     // Do not delete arguments unless we have a function body.
1525     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
1526       return false;
1527
1528     // If the callee is just a declaration, don't change the varargsness of the
1529     // call.  We don't want to introduce a varargs call where one doesn't
1530     // already exist.
1531     PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
1532     if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
1533       return false;
1534
1535     // If both the callee and the cast type are varargs, we still have to make
1536     // sure the number of fixed parameters are the same or we have the same
1537     // ABI issues as if we introduce a varargs call.
1538     if (FT->isVarArg() &&
1539         cast<FunctionType>(APTy->getElementType())->isVarArg() &&
1540         FT->getNumParams() !=
1541         cast<FunctionType>(APTy->getElementType())->getNumParams())
1542       return false;
1543   }
1544
1545   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
1546       !CallerPAL.isEmpty())
1547     // In this case we have more arguments than the new function type, but we
1548     // won't be dropping them.  Check that these extra arguments have attributes
1549     // that are compatible with being a vararg call argument.
1550     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
1551       unsigned Index = CallerPAL.getSlotIndex(i - 1);
1552       if (Index <= FT->getNumParams())
1553         break;
1554
1555       // Check if it has an attribute that's incompatible with varargs.
1556       AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
1557       if (PAttrs.hasAttribute(Index, Attribute::StructRet))
1558         return false;
1559     }
1560
1561
1562   // Okay, we decided that this is a safe thing to do: go ahead and start
1563   // inserting cast instructions as necessary.
1564   std::vector<Value*> Args;
1565   Args.reserve(NumActualArgs);
1566   SmallVector<AttributeSet, 8> attrVec;
1567   attrVec.reserve(NumCommonArgs);
1568
1569   // Get any return attributes.
1570   AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
1571
1572   // If the return value is not being used, the type may not be compatible
1573   // with the existing attributes.  Wipe out any problematic attributes.
1574   RAttrs.
1575     removeAttributes(AttributeFuncs::
1576                      typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
1577                      AttributeSet::ReturnIndex);
1578
1579   // Add the new return attributes.
1580   if (RAttrs.hasAttributes())
1581     attrVec.push_back(AttributeSet::get(Caller->getContext(),
1582                                         AttributeSet::ReturnIndex, RAttrs));
1583
1584   AI = CS.arg_begin();
1585   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1586     Type *ParamTy = FT->getParamType(i);
1587
1588     if ((*AI)->getType() == ParamTy) {
1589       Args.push_back(*AI);
1590     } else {
1591       Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
1592     }
1593
1594     // Add any parameter attributes.
1595     AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
1596     if (PAttrs.hasAttributes())
1597       attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
1598                                           PAttrs));
1599   }
1600
1601   // If the function takes more arguments than the call was taking, add them
1602   // now.
1603   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1604     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1605
1606   // If we are removing arguments to the function, emit an obnoxious warning.
1607   if (FT->getNumParams() < NumActualArgs) {
1608     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
1609     if (FT->isVarArg()) {
1610       // Add all of the arguments in their promoted form to the arg list.
1611       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1612         Type *PTy = getPromotedType((*AI)->getType());
1613         if (PTy != (*AI)->getType()) {
1614           // Must promote to pass through va_arg area!
1615           Instruction::CastOps opcode =
1616             CastInst::getCastOpcode(*AI, false, PTy, false);
1617           Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
1618         } else {
1619           Args.push_back(*AI);
1620         }
1621
1622         // Add any parameter attributes.
1623         AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
1624         if (PAttrs.hasAttributes())
1625           attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
1626                                               PAttrs));
1627       }
1628     }
1629   }
1630
1631   AttributeSet FnAttrs = CallerPAL.getFnAttributes();
1632   if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
1633     attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
1634
1635   if (NewRetTy->isVoidTy())
1636     Caller->setName("");   // Void type should not have a name.
1637
1638   const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
1639                                                        attrVec);
1640
1641   Instruction *NC;
1642   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1643     NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
1644                                II->getUnwindDest(), Args);
1645     NC->takeName(II);
1646     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1647     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1648   } else {
1649     CallInst *CI = cast<CallInst>(Caller);
1650     NC = Builder->CreateCall(Callee, Args);
1651     NC->takeName(CI);
1652     if (CI->isTailCall())
1653       cast<CallInst>(NC)->setTailCall();
1654     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1655     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1656   }
1657
1658   // Insert a cast of the return type as necessary.
1659   Value *NV = NC;
1660   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1661     if (!NV->getType()->isVoidTy()) {
1662       NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
1663       NC->setDebugLoc(Caller->getDebugLoc());
1664
1665       // If this is an invoke instruction, we should insert it after the first
1666       // non-phi, instruction in the normal successor block.
1667       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1668         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
1669         InsertNewInstBefore(NC, *I);
1670       } else {
1671         // Otherwise, it's a call, just insert cast right after the call.
1672         InsertNewInstBefore(NC, *Caller);
1673       }
1674       Worklist.AddUsersToWorkList(*Caller);
1675     } else {
1676       NV = UndefValue::get(Caller->getType());
1677     }
1678   }
1679
1680   if (!Caller->use_empty())
1681     ReplaceInstUsesWith(*Caller, NV);
1682   else if (Caller->hasValueHandle()) {
1683     if (OldRetTy == NV->getType())
1684       ValueHandleBase::ValueIsRAUWd(Caller, NV);
1685     else
1686       // We cannot call ValueIsRAUWd with a different type, and the
1687       // actual tracked value will disappear.
1688       ValueHandleBase::ValueIsDeleted(Caller);
1689   }
1690
1691   EraseInstFromFunction(*Caller);
1692   return true;
1693 }
1694
1695 // transformCallThroughTrampoline - Turn a call to a function created by
1696 // init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
1697 // underlying function.
1698 //
1699 Instruction *
1700 InstCombiner::transformCallThroughTrampoline(CallSite CS,
1701                                              IntrinsicInst *Tramp) {
1702   Value *Callee = CS.getCalledValue();
1703   PointerType *PTy = cast<PointerType>(Callee->getType());
1704   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1705   const AttributeSet &Attrs = CS.getAttributes();
1706
1707   // If the call already has the 'nest' attribute somewhere then give up -
1708   // otherwise 'nest' would occur twice after splicing in the chain.
1709   if (Attrs.hasAttrSomewhere(Attribute::Nest))
1710     return nullptr;
1711
1712   assert(Tramp &&
1713          "transformCallThroughTrampoline called with incorrect CallSite.");
1714
1715   Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
1716   PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1717   FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1718
1719   const AttributeSet &NestAttrs = NestF->getAttributes();
1720   if (!NestAttrs.isEmpty()) {
1721     unsigned NestIdx = 1;
1722     Type *NestTy = nullptr;
1723     AttributeSet NestAttr;
1724
1725     // Look for a parameter marked with the 'nest' attribute.
1726     for (FunctionType::param_iterator I = NestFTy->param_begin(),
1727          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1728       if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
1729         // Record the parameter type and any other attributes.
1730         NestTy = *I;
1731         NestAttr = NestAttrs.getParamAttributes(NestIdx);
1732         break;
1733       }
1734
1735     if (NestTy) {
1736       Instruction *Caller = CS.getInstruction();
1737       std::vector<Value*> NewArgs;
1738       NewArgs.reserve(CS.arg_size() + 1);
1739
1740       SmallVector<AttributeSet, 8> NewAttrs;
1741       NewAttrs.reserve(Attrs.getNumSlots() + 1);
1742
1743       // Insert the nest argument into the call argument list, which may
1744       // mean appending it.  Likewise for attributes.
1745
1746       // Add any result attributes.
1747       if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
1748         NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1749                                              Attrs.getRetAttributes()));
1750
1751       {
1752         unsigned Idx = 1;
1753         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1754         do {
1755           if (Idx == NestIdx) {
1756             // Add the chain argument and attributes.
1757             Value *NestVal = Tramp->getArgOperand(2);
1758             if (NestVal->getType() != NestTy)
1759               NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
1760             NewArgs.push_back(NestVal);
1761             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1762                                                  NestAttr));
1763           }
1764
1765           if (I == E)
1766             break;
1767
1768           // Add the original argument and attributes.
1769           NewArgs.push_back(*I);
1770           AttributeSet Attr = Attrs.getParamAttributes(Idx);
1771           if (Attr.hasAttributes(Idx)) {
1772             AttrBuilder B(Attr, Idx);
1773             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1774                                                  Idx + (Idx >= NestIdx), B));
1775           }
1776
1777           ++Idx, ++I;
1778         } while (1);
1779       }
1780
1781       // Add any function attributes.
1782       if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
1783         NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
1784                                              Attrs.getFnAttributes()));
1785
1786       // The trampoline may have been bitcast to a bogus type (FTy).
1787       // Handle this by synthesizing a new function type, equal to FTy
1788       // with the chain parameter inserted.
1789
1790       std::vector<Type*> NewTypes;
1791       NewTypes.reserve(FTy->getNumParams()+1);
1792
1793       // Insert the chain's type into the list of parameter types, which may
1794       // mean appending it.
1795       {
1796         unsigned Idx = 1;
1797         FunctionType::param_iterator I = FTy->param_begin(),
1798           E = FTy->param_end();
1799
1800         do {
1801           if (Idx == NestIdx)
1802             // Add the chain's type.
1803             NewTypes.push_back(NestTy);
1804
1805           if (I == E)
1806             break;
1807
1808           // Add the original type.
1809           NewTypes.push_back(*I);
1810
1811           ++Idx, ++I;
1812         } while (1);
1813       }
1814
1815       // Replace the trampoline call with a direct call.  Let the generic
1816       // code sort out any function type mismatches.
1817       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
1818                                                 FTy->isVarArg());
1819       Constant *NewCallee =
1820         NestF->getType() == PointerType::getUnqual(NewFTy) ?
1821         NestF : ConstantExpr::getBitCast(NestF,
1822                                          PointerType::getUnqual(NewFTy));
1823       const AttributeSet &NewPAL =
1824           AttributeSet::get(FTy->getContext(), NewAttrs);
1825
1826       Instruction *NewCaller;
1827       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1828         NewCaller = InvokeInst::Create(NewCallee,
1829                                        II->getNormalDest(), II->getUnwindDest(),
1830                                        NewArgs);
1831         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1832         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1833       } else {
1834         NewCaller = CallInst::Create(NewCallee, NewArgs);
1835         if (cast<CallInst>(Caller)->isTailCall())
1836           cast<CallInst>(NewCaller)->setTailCall();
1837         cast<CallInst>(NewCaller)->
1838           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1839         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1840       }
1841
1842       return NewCaller;
1843     }
1844   }
1845
1846   // Replace the trampoline call with a direct call.  Since there is no 'nest'
1847   // parameter, there is no need to adjust the argument list.  Let the generic
1848   // code sort out any function type mismatches.
1849   Constant *NewCallee =
1850     NestF->getType() == PTy ? NestF :
1851                               ConstantExpr::getBitCast(NestF, PTy);
1852   CS.setCalledFunction(NewCallee);
1853   return CS.getInstruction();
1854 }