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/InstructionSimplify.h" 17 #include "llvm/Analysis/Loads.h" 18 #include "llvm/Analysis/MemoryBuiltins.h" 19 #include "llvm/IR/CallSite.h" 20 #include "llvm/IR/Dominators.h" 21 #include "llvm/IR/PatternMatch.h" 22 #include "llvm/IR/Statepoint.h" 23 #include "llvm/Transforms/Utils/BuildLibCalls.h" 24 #include "llvm/Transforms/Utils/Local.h" 25 #include "llvm/Transforms/Utils/SimplifyLibCalls.h" 26 using namespace llvm; 27 using namespace PatternMatch; 28 29 #define DEBUG_TYPE "instcombine" 30 31 STATISTIC(NumSimplified, "Number of library calls simplified"); 32 33 /// Return the specified type promoted as it would be to pass though a va_arg 34 /// area. 35 static Type *getPromotedType(Type *Ty) { 36 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) { 37 if (ITy->getBitWidth() < 32) 38 return Type::getInt32Ty(Ty->getContext()); 39 } 40 return Ty; 41 } 42 43 /// Given an aggregate type which ultimately holds a single scalar element, 44 /// like {{{type}}} or [1 x type], return type. 45 static Type *reduceToSingleValueType(Type *T) { 46 while (!T->isSingleValueType()) { 47 if (StructType *STy = dyn_cast<StructType>(T)) { 48 if (STy->getNumElements() == 1) 49 T = STy->getElementType(0); 50 else 51 break; 52 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) { 53 if (ATy->getNumElements() == 1) 54 T = ATy->getElementType(); 55 else 56 break; 57 } else 58 break; 59 } 60 61 return T; 62 } 63 64 /// Return a constant boolean vector that has true elements in all positions 65 /// where the input constant data vector has an element with the sign bit set. 66 static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) { 67 SmallVector<Constant *, 32> BoolVec; 68 IntegerType *BoolTy = Type::getInt1Ty(V->getContext()); 69 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) { 70 Constant *Elt = V->getElementAsConstant(I); 71 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) && 72 "Unexpected constant data vector element type"); 73 bool Sign = V->getElementType()->isIntegerTy() 74 ? cast<ConstantInt>(Elt)->isNegative() 75 : cast<ConstantFP>(Elt)->isNegative(); 76 BoolVec.push_back(ConstantInt::get(BoolTy, Sign)); 77 } 78 return ConstantVector::get(BoolVec); 79 } 80 81 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) { 82 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, AC, DT); 83 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, AC, DT); 84 unsigned MinAlign = std::min(DstAlign, SrcAlign); 85 unsigned CopyAlign = MI->getAlignment(); 86 87 if (CopyAlign < MinAlign) { 88 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false)); 89 return MI; 90 } 91 92 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with 93 // load/store. 94 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2)); 95 if (!MemOpLength) return nullptr; 96 97 // Source and destination pointer types are always "i8*" for intrinsic. See 98 // if the size is something we can handle with a single primitive load/store. 99 // A single load+store correctly handles overlapping memory in the memmove 100 // case. 101 uint64_t Size = MemOpLength->getLimitedValue(); 102 assert(Size && "0-sized memory transferring should be removed already."); 103 104 if (Size > 8 || (Size&(Size-1))) 105 return nullptr; // If not 1/2/4/8 bytes, exit. 106 107 // Use an integer load+store unless we can find something better. 108 unsigned SrcAddrSp = 109 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace(); 110 unsigned DstAddrSp = 111 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace(); 112 113 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3); 114 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp); 115 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp); 116 117 // Memcpy forces the use of i8* for the source and destination. That means 118 // that if you're using memcpy to move one double around, you'll get a cast 119 // from double* to i8*. We'd much rather use a double load+store rather than 120 // an i64 load+store, here because this improves the odds that the source or 121 // dest address will be promotable. See if we can find a better type than the 122 // integer datatype. 123 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts(); 124 MDNode *CopyMD = nullptr; 125 if (StrippedDest != MI->getArgOperand(0)) { 126 Type *SrcETy = cast<PointerType>(StrippedDest->getType()) 127 ->getElementType(); 128 if (SrcETy->isSized() && DL.getTypeStoreSize(SrcETy) == Size) { 129 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip 130 // down through these levels if so. 131 SrcETy = reduceToSingleValueType(SrcETy); 132 133 if (SrcETy->isSingleValueType()) { 134 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp); 135 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp); 136 137 // If the memcpy has metadata describing the members, see if we can 138 // get the TBAA tag describing our copy. 139 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) { 140 if (M->getNumOperands() == 3 && M->getOperand(0) && 141 mdconst::hasa<ConstantInt>(M->getOperand(0)) && 142 mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() && 143 M->getOperand(1) && 144 mdconst::hasa<ConstantInt>(M->getOperand(1)) && 145 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() == 146 Size && 147 M->getOperand(2) && isa<MDNode>(M->getOperand(2))) 148 CopyMD = cast<MDNode>(M->getOperand(2)); 149 } 150 } 151 } 152 } 153 154 // If the memcpy/memmove provides better alignment info than we can 155 // infer, use it. 156 SrcAlign = std::max(SrcAlign, CopyAlign); 157 DstAlign = std::max(DstAlign, CopyAlign); 158 159 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy); 160 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy); 161 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile()); 162 L->setAlignment(SrcAlign); 163 if (CopyMD) 164 L->setMetadata(LLVMContext::MD_tbaa, CopyMD); 165 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile()); 166 S->setAlignment(DstAlign); 167 if (CopyMD) 168 S->setMetadata(LLVMContext::MD_tbaa, CopyMD); 169 170 // Set the size of the copy to 0, it will be deleted on the next iteration. 171 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType())); 172 return MI; 173 } 174 175 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) { 176 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, AC, DT); 177 if (MI->getAlignment() < Alignment) { 178 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 179 Alignment, false)); 180 return MI; 181 } 182 183 // Extract the length and alignment and fill if they are constant. 184 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength()); 185 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue()); 186 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8)) 187 return nullptr; 188 uint64_t Len = LenC->getLimitedValue(); 189 Alignment = MI->getAlignment(); 190 assert(Len && "0-sized memory setting should be removed already."); 191 192 // memset(s,c,n) -> store s, c (for n=1,2,4,8) 193 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) { 194 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8. 195 196 Value *Dest = MI->getDest(); 197 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace(); 198 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp); 199 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy); 200 201 // Alignment 0 is identity for alignment 1 for memset, but not store. 202 if (Alignment == 0) Alignment = 1; 203 204 // Extract the fill value and store. 205 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL; 206 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest, 207 MI->isVolatile()); 208 S->setAlignment(Alignment); 209 210 // Set the size of the copy to 0, it will be deleted on the next iteration. 211 MI->setLength(Constant::getNullValue(LenC->getType())); 212 return MI; 213 } 214 215 return nullptr; 216 } 217 218 static Value *simplifyX86immShift(const IntrinsicInst &II, 219 InstCombiner::BuilderTy &Builder) { 220 bool LogicalShift = false; 221 bool ShiftLeft = false; 222 223 switch (II.getIntrinsicID()) { 224 default: 225 return nullptr; 226 case Intrinsic::x86_sse2_psra_d: 227 case Intrinsic::x86_sse2_psra_w: 228 case Intrinsic::x86_sse2_psrai_d: 229 case Intrinsic::x86_sse2_psrai_w: 230 case Intrinsic::x86_avx2_psra_d: 231 case Intrinsic::x86_avx2_psra_w: 232 case Intrinsic::x86_avx2_psrai_d: 233 case Intrinsic::x86_avx2_psrai_w: 234 LogicalShift = false; ShiftLeft = false; 235 break; 236 case Intrinsic::x86_sse2_psrl_d: 237 case Intrinsic::x86_sse2_psrl_q: 238 case Intrinsic::x86_sse2_psrl_w: 239 case Intrinsic::x86_sse2_psrli_d: 240 case Intrinsic::x86_sse2_psrli_q: 241 case Intrinsic::x86_sse2_psrli_w: 242 case Intrinsic::x86_avx2_psrl_d: 243 case Intrinsic::x86_avx2_psrl_q: 244 case Intrinsic::x86_avx2_psrl_w: 245 case Intrinsic::x86_avx2_psrli_d: 246 case Intrinsic::x86_avx2_psrli_q: 247 case Intrinsic::x86_avx2_psrli_w: 248 LogicalShift = true; ShiftLeft = false; 249 break; 250 case Intrinsic::x86_sse2_psll_d: 251 case Intrinsic::x86_sse2_psll_q: 252 case Intrinsic::x86_sse2_psll_w: 253 case Intrinsic::x86_sse2_pslli_d: 254 case Intrinsic::x86_sse2_pslli_q: 255 case Intrinsic::x86_sse2_pslli_w: 256 case Intrinsic::x86_avx2_psll_d: 257 case Intrinsic::x86_avx2_psll_q: 258 case Intrinsic::x86_avx2_psll_w: 259 case Intrinsic::x86_avx2_pslli_d: 260 case Intrinsic::x86_avx2_pslli_q: 261 case Intrinsic::x86_avx2_pslli_w: 262 LogicalShift = true; ShiftLeft = true; 263 break; 264 } 265 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left"); 266 267 // Simplify if count is constant. 268 auto Arg1 = II.getArgOperand(1); 269 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1); 270 auto CDV = dyn_cast<ConstantDataVector>(Arg1); 271 auto CInt = dyn_cast<ConstantInt>(Arg1); 272 if (!CAZ && !CDV && !CInt) 273 return nullptr; 274 275 APInt Count(64, 0); 276 if (CDV) { 277 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector 278 // operand to compute the shift amount. 279 auto VT = cast<VectorType>(CDV->getType()); 280 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits(); 281 assert((64 % BitWidth) == 0 && "Unexpected packed shift size"); 282 unsigned NumSubElts = 64 / BitWidth; 283 284 // Concatenate the sub-elements to create the 64-bit value. 285 for (unsigned i = 0; i != NumSubElts; ++i) { 286 unsigned SubEltIdx = (NumSubElts - 1) - i; 287 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx)); 288 Count = Count.shl(BitWidth); 289 Count |= SubElt->getValue().zextOrTrunc(64); 290 } 291 } 292 else if (CInt) 293 Count = CInt->getValue(); 294 295 auto Vec = II.getArgOperand(0); 296 auto VT = cast<VectorType>(Vec->getType()); 297 auto SVT = VT->getElementType(); 298 unsigned VWidth = VT->getNumElements(); 299 unsigned BitWidth = SVT->getPrimitiveSizeInBits(); 300 301 // If shift-by-zero then just return the original value. 302 if (Count == 0) 303 return Vec; 304 305 // Handle cases when Shift >= BitWidth. 306 if (Count.uge(BitWidth)) { 307 // If LogicalShift - just return zero. 308 if (LogicalShift) 309 return ConstantAggregateZero::get(VT); 310 311 // If ArithmeticShift - clamp Shift to (BitWidth - 1). 312 Count = APInt(64, BitWidth - 1); 313 } 314 315 // Get a constant vector of the same type as the first operand. 316 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth)); 317 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt); 318 319 if (ShiftLeft) 320 return Builder.CreateShl(Vec, ShiftVec); 321 322 if (LogicalShift) 323 return Builder.CreateLShr(Vec, ShiftVec); 324 325 return Builder.CreateAShr(Vec, ShiftVec); 326 } 327 328 static Value *simplifyX86extend(const IntrinsicInst &II, 329 InstCombiner::BuilderTy &Builder, 330 bool SignExtend) { 331 VectorType *SrcTy = cast<VectorType>(II.getArgOperand(0)->getType()); 332 VectorType *DstTy = cast<VectorType>(II.getType()); 333 unsigned NumDstElts = DstTy->getNumElements(); 334 335 // Extract a subvector of the first NumDstElts lanes and sign/zero extend. 336 SmallVector<int, 8> ShuffleMask; 337 for (int i = 0; i != (int)NumDstElts; ++i) 338 ShuffleMask.push_back(i); 339 340 Value *SV = Builder.CreateShuffleVector(II.getArgOperand(0), 341 UndefValue::get(SrcTy), ShuffleMask); 342 return SignExtend ? Builder.CreateSExt(SV, DstTy) 343 : Builder.CreateZExt(SV, DstTy); 344 } 345 346 static Value *simplifyX86insertps(const IntrinsicInst &II, 347 InstCombiner::BuilderTy &Builder) { 348 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2)); 349 if (!CInt) 350 return nullptr; 351 352 VectorType *VecTy = cast<VectorType>(II.getType()); 353 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type"); 354 355 // The immediate permute control byte looks like this: 356 // [3:0] - zero mask for each 32-bit lane 357 // [5:4] - select one 32-bit destination lane 358 // [7:6] - select one 32-bit source lane 359 360 uint8_t Imm = CInt->getZExtValue(); 361 uint8_t ZMask = Imm & 0xf; 362 uint8_t DestLane = (Imm >> 4) & 0x3; 363 uint8_t SourceLane = (Imm >> 6) & 0x3; 364 365 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy); 366 367 // If all zero mask bits are set, this was just a weird way to 368 // generate a zero vector. 369 if (ZMask == 0xf) 370 return ZeroVector; 371 372 // Initialize by passing all of the first source bits through. 373 int ShuffleMask[4] = { 0, 1, 2, 3 }; 374 375 // We may replace the second operand with the zero vector. 376 Value *V1 = II.getArgOperand(1); 377 378 if (ZMask) { 379 // If the zero mask is being used with a single input or the zero mask 380 // overrides the destination lane, this is a shuffle with the zero vector. 381 if ((II.getArgOperand(0) == II.getArgOperand(1)) || 382 (ZMask & (1 << DestLane))) { 383 V1 = ZeroVector; 384 // We may still move 32-bits of the first source vector from one lane 385 // to another. 386 ShuffleMask[DestLane] = SourceLane; 387 // The zero mask may override the previous insert operation. 388 for (unsigned i = 0; i < 4; ++i) 389 if ((ZMask >> i) & 0x1) 390 ShuffleMask[i] = i + 4; 391 } else { 392 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle? 393 return nullptr; 394 } 395 } else { 396 // Replace the selected destination lane with the selected source lane. 397 ShuffleMask[DestLane] = SourceLane + 4; 398 } 399 400 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask); 401 } 402 403 /// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding 404 /// or conversion to a shuffle vector. 405 static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0, 406 ConstantInt *CILength, ConstantInt *CIIndex, 407 InstCombiner::BuilderTy &Builder) { 408 auto LowConstantHighUndef = [&](uint64_t Val) { 409 Type *IntTy64 = Type::getInt64Ty(II.getContext()); 410 Constant *Args[] = {ConstantInt::get(IntTy64, Val), 411 UndefValue::get(IntTy64)}; 412 return ConstantVector::get(Args); 413 }; 414 415 // See if we're dealing with constant values. 416 Constant *C0 = dyn_cast<Constant>(Op0); 417 ConstantInt *CI0 = 418 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0)) 419 : nullptr; 420 421 // Attempt to constant fold. 422 if (CILength && CIIndex) { 423 // From AMD documentation: "The bit index and field length are each six 424 // bits in length other bits of the field are ignored." 425 APInt APIndex = CIIndex->getValue().zextOrTrunc(6); 426 APInt APLength = CILength->getValue().zextOrTrunc(6); 427 428 unsigned Index = APIndex.getZExtValue(); 429 430 // From AMD documentation: "a value of zero in the field length is 431 // defined as length of 64". 432 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue(); 433 434 // From AMD documentation: "If the sum of the bit index + length field 435 // is greater than 64, the results are undefined". 436 unsigned End = Index + Length; 437 438 // Note that both field index and field length are 8-bit quantities. 439 // Since variables 'Index' and 'Length' are unsigned values 440 // obtained from zero-extending field index and field length 441 // respectively, their sum should never wrap around. 442 if (End > 64) 443 return UndefValue::get(II.getType()); 444 445 // If we are inserting whole bytes, we can convert this to a shuffle. 446 // Lowering can recognize EXTRQI shuffle masks. 447 if ((Length % 8) == 0 && (Index % 8) == 0) { 448 // Convert bit indices to byte indices. 449 Length /= 8; 450 Index /= 8; 451 452 Type *IntTy8 = Type::getInt8Ty(II.getContext()); 453 Type *IntTy32 = Type::getInt32Ty(II.getContext()); 454 VectorType *ShufTy = VectorType::get(IntTy8, 16); 455 456 SmallVector<Constant *, 16> ShuffleMask; 457 for (int i = 0; i != (int)Length; ++i) 458 ShuffleMask.push_back( 459 Constant::getIntegerValue(IntTy32, APInt(32, i + Index))); 460 for (int i = Length; i != 8; ++i) 461 ShuffleMask.push_back( 462 Constant::getIntegerValue(IntTy32, APInt(32, i + 16))); 463 for (int i = 8; i != 16; ++i) 464 ShuffleMask.push_back(UndefValue::get(IntTy32)); 465 466 Value *SV = Builder.CreateShuffleVector( 467 Builder.CreateBitCast(Op0, ShufTy), 468 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask)); 469 return Builder.CreateBitCast(SV, II.getType()); 470 } 471 472 // Constant Fold - shift Index'th bit to lowest position and mask off 473 // Length bits. 474 if (CI0) { 475 APInt Elt = CI0->getValue(); 476 Elt = Elt.lshr(Index).zextOrTrunc(Length); 477 return LowConstantHighUndef(Elt.getZExtValue()); 478 } 479 480 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI. 481 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) { 482 Value *Args[] = {Op0, CILength, CIIndex}; 483 Module *M = II.getModule(); 484 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi); 485 return Builder.CreateCall(F, Args); 486 } 487 } 488 489 // Constant Fold - extraction from zero is always {zero, undef}. 490 if (CI0 && CI0->equalsInt(0)) 491 return LowConstantHighUndef(0); 492 493 return nullptr; 494 } 495 496 /// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant 497 /// folding or conversion to a shuffle vector. 498 static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1, 499 APInt APLength, APInt APIndex, 500 InstCombiner::BuilderTy &Builder) { 501 502 // From AMD documentation: "The bit index and field length are each six bits 503 // in length other bits of the field are ignored." 504 APIndex = APIndex.zextOrTrunc(6); 505 APLength = APLength.zextOrTrunc(6); 506 507 // Attempt to constant fold. 508 unsigned Index = APIndex.getZExtValue(); 509 510 // From AMD documentation: "a value of zero in the field length is 511 // defined as length of 64". 512 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue(); 513 514 // From AMD documentation: "If the sum of the bit index + length field 515 // is greater than 64, the results are undefined". 516 unsigned End = Index + Length; 517 518 // Note that both field index and field length are 8-bit quantities. 519 // Since variables 'Index' and 'Length' are unsigned values 520 // obtained from zero-extending field index and field length 521 // respectively, their sum should never wrap around. 522 if (End > 64) 523 return UndefValue::get(II.getType()); 524 525 // If we are inserting whole bytes, we can convert this to a shuffle. 526 // Lowering can recognize INSERTQI shuffle masks. 527 if ((Length % 8) == 0 && (Index % 8) == 0) { 528 // Convert bit indices to byte indices. 529 Length /= 8; 530 Index /= 8; 531 532 Type *IntTy8 = Type::getInt8Ty(II.getContext()); 533 Type *IntTy32 = Type::getInt32Ty(II.getContext()); 534 VectorType *ShufTy = VectorType::get(IntTy8, 16); 535 536 SmallVector<Constant *, 16> ShuffleMask; 537 for (int i = 0; i != (int)Index; ++i) 538 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i))); 539 for (int i = 0; i != (int)Length; ++i) 540 ShuffleMask.push_back( 541 Constant::getIntegerValue(IntTy32, APInt(32, i + 16))); 542 for (int i = Index + Length; i != 8; ++i) 543 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i))); 544 for (int i = 8; i != 16; ++i) 545 ShuffleMask.push_back(UndefValue::get(IntTy32)); 546 547 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy), 548 Builder.CreateBitCast(Op1, ShufTy), 549 ConstantVector::get(ShuffleMask)); 550 return Builder.CreateBitCast(SV, II.getType()); 551 } 552 553 // See if we're dealing with constant values. 554 Constant *C0 = dyn_cast<Constant>(Op0); 555 Constant *C1 = dyn_cast<Constant>(Op1); 556 ConstantInt *CI00 = 557 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0)) 558 : nullptr; 559 ConstantInt *CI10 = 560 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0)) 561 : nullptr; 562 563 // Constant Fold - insert bottom Length bits starting at the Index'th bit. 564 if (CI00 && CI10) { 565 APInt V00 = CI00->getValue(); 566 APInt V10 = CI10->getValue(); 567 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index); 568 V00 = V00 & ~Mask; 569 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index); 570 APInt Val = V00 | V10; 571 Type *IntTy64 = Type::getInt64Ty(II.getContext()); 572 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()), 573 UndefValue::get(IntTy64)}; 574 return ConstantVector::get(Args); 575 } 576 577 // If we were an INSERTQ call, we'll save demanded elements if we convert to 578 // INSERTQI. 579 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) { 580 Type *IntTy8 = Type::getInt8Ty(II.getContext()); 581 Constant *CILength = ConstantInt::get(IntTy8, Length, false); 582 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false); 583 584 Value *Args[] = {Op0, Op1, CILength, CIIndex}; 585 Module *M = II.getModule(); 586 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi); 587 return Builder.CreateCall(F, Args); 588 } 589 590 return nullptr; 591 } 592 593 /// The shuffle mask for a perm2*128 selects any two halves of two 256-bit 594 /// source vectors, unless a zero bit is set. If a zero bit is set, 595 /// then ignore that half of the mask and clear that half of the vector. 596 static Value *simplifyX86vperm2(const IntrinsicInst &II, 597 InstCombiner::BuilderTy &Builder) { 598 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2)); 599 if (!CInt) 600 return nullptr; 601 602 VectorType *VecTy = cast<VectorType>(II.getType()); 603 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy); 604 605 // The immediate permute control byte looks like this: 606 // [1:0] - select 128 bits from sources for low half of destination 607 // [2] - ignore 608 // [3] - zero low half of destination 609 // [5:4] - select 128 bits from sources for high half of destination 610 // [6] - ignore 611 // [7] - zero high half of destination 612 613 uint8_t Imm = CInt->getZExtValue(); 614 615 bool LowHalfZero = Imm & 0x08; 616 bool HighHalfZero = Imm & 0x80; 617 618 // If both zero mask bits are set, this was just a weird way to 619 // generate a zero vector. 620 if (LowHalfZero && HighHalfZero) 621 return ZeroVector; 622 623 // If 0 or 1 zero mask bits are set, this is a simple shuffle. 624 unsigned NumElts = VecTy->getNumElements(); 625 unsigned HalfSize = NumElts / 2; 626 SmallVector<int, 8> ShuffleMask(NumElts); 627 628 // The high bit of the selection field chooses the 1st or 2nd operand. 629 bool LowInputSelect = Imm & 0x02; 630 bool HighInputSelect = Imm & 0x20; 631 632 // The low bit of the selection field chooses the low or high half 633 // of the selected operand. 634 bool LowHalfSelect = Imm & 0x01; 635 bool HighHalfSelect = Imm & 0x10; 636 637 // Determine which operand(s) are actually in use for this instruction. 638 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0); 639 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0); 640 641 // If needed, replace operands based on zero mask. 642 V0 = LowHalfZero ? ZeroVector : V0; 643 V1 = HighHalfZero ? ZeroVector : V1; 644 645 // Permute low half of result. 646 unsigned StartIndex = LowHalfSelect ? HalfSize : 0; 647 for (unsigned i = 0; i < HalfSize; ++i) 648 ShuffleMask[i] = StartIndex + i; 649 650 // Permute high half of result. 651 StartIndex = HighHalfSelect ? HalfSize : 0; 652 StartIndex += NumElts; 653 for (unsigned i = 0; i < HalfSize; ++i) 654 ShuffleMask[i + HalfSize] = StartIndex + i; 655 656 return Builder.CreateShuffleVector(V0, V1, ShuffleMask); 657 } 658 659 /// Decode XOP integer vector comparison intrinsics. 660 static Value *simplifyX86vpcom(const IntrinsicInst &II, 661 InstCombiner::BuilderTy &Builder, 662 bool IsSigned) { 663 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) { 664 uint64_t Imm = CInt->getZExtValue() & 0x7; 665 VectorType *VecTy = cast<VectorType>(II.getType()); 666 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 667 668 switch (Imm) { 669 case 0x0: 670 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 671 break; 672 case 0x1: 673 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 674 break; 675 case 0x2: 676 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 677 break; 678 case 0x3: 679 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 680 break; 681 case 0x4: 682 Pred = ICmpInst::ICMP_EQ; break; 683 case 0x5: 684 Pred = ICmpInst::ICMP_NE; break; 685 case 0x6: 686 return ConstantInt::getSigned(VecTy, 0); // FALSE 687 case 0x7: 688 return ConstantInt::getSigned(VecTy, -1); // TRUE 689 } 690 691 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0), 692 II.getArgOperand(1))) 693 return Builder.CreateSExtOrTrunc(Cmp, VecTy); 694 } 695 return nullptr; 696 } 697 698 static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) { 699 Value *Arg0 = II.getArgOperand(0); 700 Value *Arg1 = II.getArgOperand(1); 701 702 // fmin(x, x) -> x 703 if (Arg0 == Arg1) 704 return Arg0; 705 706 const auto *C1 = dyn_cast<ConstantFP>(Arg1); 707 708 // fmin(x, nan) -> x 709 if (C1 && C1->isNaN()) 710 return Arg0; 711 712 // This is the value because if undef were NaN, we would return the other 713 // value and cannot return a NaN unless both operands are. 714 // 715 // fmin(undef, x) -> x 716 if (isa<UndefValue>(Arg0)) 717 return Arg1; 718 719 // fmin(x, undef) -> x 720 if (isa<UndefValue>(Arg1)) 721 return Arg0; 722 723 Value *X = nullptr; 724 Value *Y = nullptr; 725 if (II.getIntrinsicID() == Intrinsic::minnum) { 726 // fmin(x, fmin(x, y)) -> fmin(x, y) 727 // fmin(y, fmin(x, y)) -> fmin(x, y) 728 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) { 729 if (Arg0 == X || Arg0 == Y) 730 return Arg1; 731 } 732 733 // fmin(fmin(x, y), x) -> fmin(x, y) 734 // fmin(fmin(x, y), y) -> fmin(x, y) 735 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) { 736 if (Arg1 == X || Arg1 == Y) 737 return Arg0; 738 } 739 740 // TODO: fmin(nnan x, inf) -> x 741 // TODO: fmin(nnan ninf x, flt_max) -> x 742 if (C1 && C1->isInfinity()) { 743 // fmin(x, -inf) -> -inf 744 if (C1->isNegative()) 745 return Arg1; 746 } 747 } else { 748 assert(II.getIntrinsicID() == Intrinsic::maxnum); 749 // fmax(x, fmax(x, y)) -> fmax(x, y) 750 // fmax(y, fmax(x, y)) -> fmax(x, y) 751 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) { 752 if (Arg0 == X || Arg0 == Y) 753 return Arg1; 754 } 755 756 // fmax(fmax(x, y), x) -> fmax(x, y) 757 // fmax(fmax(x, y), y) -> fmax(x, y) 758 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) { 759 if (Arg1 == X || Arg1 == Y) 760 return Arg0; 761 } 762 763 // TODO: fmax(nnan x, -inf) -> x 764 // TODO: fmax(nnan ninf x, -flt_max) -> x 765 if (C1 && C1->isInfinity()) { 766 // fmax(x, inf) -> inf 767 if (!C1->isNegative()) 768 return Arg1; 769 } 770 } 771 return nullptr; 772 } 773 774 static Value *simplifyMaskedLoad(const IntrinsicInst &II, 775 InstCombiner::BuilderTy &Builder) { 776 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2)); 777 if (!ConstMask) 778 return nullptr; 779 780 // If the mask is all zeros, the "passthru" argument is the result. 781 if (ConstMask->isNullValue()) 782 return II.getArgOperand(3); 783 784 // If the mask is all ones, this is a plain vector load of the 1st argument. 785 if (ConstMask->isAllOnesValue()) { 786 Value *LoadPtr = II.getArgOperand(0); 787 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue(); 788 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload"); 789 } 790 791 return nullptr; 792 } 793 794 static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) { 795 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3)); 796 if (!ConstMask) 797 return nullptr; 798 799 // If the mask is all zeros, this instruction does nothing. 800 if (ConstMask->isNullValue()) 801 return IC.eraseInstFromFunction(II); 802 803 // If the mask is all ones, this is a plain vector store of the 1st argument. 804 if (ConstMask->isAllOnesValue()) { 805 Value *StorePtr = II.getArgOperand(1); 806 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue(); 807 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment); 808 } 809 810 return nullptr; 811 } 812 813 static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) { 814 // If the mask is all zeros, return the "passthru" argument of the gather. 815 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2)); 816 if (ConstMask && ConstMask->isNullValue()) 817 return IC.replaceInstUsesWith(II, II.getArgOperand(3)); 818 819 return nullptr; 820 } 821 822 static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) { 823 // If the mask is all zeros, a scatter does nothing. 824 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3)); 825 if (ConstMask && ConstMask->isNullValue()) 826 return IC.eraseInstFromFunction(II); 827 828 return nullptr; 829 } 830 831 // TODO: If the x86 backend knew how to convert a bool vector mask back to an 832 // XMM register mask efficiently, we could transform all x86 masked intrinsics 833 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs. 834 static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) { 835 Value *Ptr = II.getOperand(0); 836 Value *Mask = II.getOperand(1); 837 Value *Vec = II.getOperand(2); 838 839 // Special case a zero mask since that's not a ConstantDataVector: 840 // this masked store instruction does nothing. 841 if (isa<ConstantAggregateZero>(Mask)) { 842 IC.eraseInstFromFunction(II); 843 return true; 844 } 845 846 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask); 847 if (!ConstMask) 848 return false; 849 850 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic 851 // to allow target-independent optimizations. 852 853 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match 854 // the LLVM intrinsic definition for the pointer argument. 855 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace(); 856 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace); 857 858 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec"); 859 860 // Second, convert the x86 XMM integer vector mask to a vector of bools based 861 // on each element's most significant bit (the sign bit). 862 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask); 863 864 IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask); 865 866 // 'Replace uses' doesn't work for stores. Erase the original masked store. 867 IC.eraseInstFromFunction(II); 868 return true; 869 } 870 871 /// CallInst simplification. This mostly only handles folding of intrinsic 872 /// instructions. For normal calls, it allows visitCallSite to do the heavy 873 /// lifting. 874 Instruction *InstCombiner::visitCallInst(CallInst &CI) { 875 auto Args = CI.arg_operands(); 876 if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL, 877 TLI, DT, AC)) 878 return replaceInstUsesWith(CI, V); 879 880 if (isFreeCall(&CI, TLI)) 881 return visitFree(CI); 882 883 // If the caller function is nounwind, mark the call as nounwind, even if the 884 // callee isn't. 885 if (CI.getParent()->getParent()->doesNotThrow() && 886 !CI.doesNotThrow()) { 887 CI.setDoesNotThrow(); 888 return &CI; 889 } 890 891 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI); 892 if (!II) return visitCallSite(&CI); 893 894 // Intrinsics cannot occur in an invoke, so handle them here instead of in 895 // visitCallSite. 896 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) { 897 bool Changed = false; 898 899 // memmove/cpy/set of zero bytes is a noop. 900 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) { 901 if (NumBytes->isNullValue()) 902 return eraseInstFromFunction(CI); 903 904 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes)) 905 if (CI->getZExtValue() == 1) { 906 // Replace the instruction with just byte operations. We would 907 // transform other cases to loads/stores, but we don't know if 908 // alignment is sufficient. 909 } 910 } 911 912 // No other transformations apply to volatile transfers. 913 if (MI->isVolatile()) 914 return nullptr; 915 916 // If we have a memmove and the source operation is a constant global, 917 // then the source and dest pointers can't alias, so we can change this 918 // into a call to memcpy. 919 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) { 920 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource())) 921 if (GVSrc->isConstant()) { 922 Module *M = CI.getModule(); 923 Intrinsic::ID MemCpyID = Intrinsic::memcpy; 924 Type *Tys[3] = { CI.getArgOperand(0)->getType(), 925 CI.getArgOperand(1)->getType(), 926 CI.getArgOperand(2)->getType() }; 927 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys)); 928 Changed = true; 929 } 930 } 931 932 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { 933 // memmove(x,x,size) -> noop. 934 if (MTI->getSource() == MTI->getDest()) 935 return eraseInstFromFunction(CI); 936 } 937 938 // If we can determine a pointer alignment that is bigger than currently 939 // set, update the alignment. 940 if (isa<MemTransferInst>(MI)) { 941 if (Instruction *I = SimplifyMemTransfer(MI)) 942 return I; 943 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) { 944 if (Instruction *I = SimplifyMemSet(MSI)) 945 return I; 946 } 947 948 if (Changed) return II; 949 } 950 951 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width, 952 unsigned DemandedWidth) { 953 APInt UndefElts(Width, 0); 954 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth); 955 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts); 956 }; 957 958 switch (II->getIntrinsicID()) { 959 default: break; 960 case Intrinsic::objectsize: { 961 uint64_t Size; 962 if (getObjectSize(II->getArgOperand(0), Size, DL, TLI)) 963 return replaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size)); 964 return nullptr; 965 } 966 case Intrinsic::bswap: { 967 Value *IIOperand = II->getArgOperand(0); 968 Value *X = nullptr; 969 970 // bswap(bswap(x)) -> x 971 if (match(IIOperand, m_BSwap(m_Value(X)))) 972 return replaceInstUsesWith(CI, X); 973 974 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c)) 975 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) { 976 unsigned C = X->getType()->getPrimitiveSizeInBits() - 977 IIOperand->getType()->getPrimitiveSizeInBits(); 978 Value *CV = ConstantInt::get(X->getType(), C); 979 Value *V = Builder->CreateLShr(X, CV); 980 return new TruncInst(V, IIOperand->getType()); 981 } 982 break; 983 } 984 985 case Intrinsic::bitreverse: { 986 Value *IIOperand = II->getArgOperand(0); 987 Value *X = nullptr; 988 989 // bitreverse(bitreverse(x)) -> x 990 if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X)))) 991 return replaceInstUsesWith(CI, X); 992 break; 993 } 994 995 case Intrinsic::masked_load: 996 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder)) 997 return replaceInstUsesWith(CI, SimplifiedMaskedOp); 998 break; 999 case Intrinsic::masked_store: 1000 return simplifyMaskedStore(*II, *this); 1001 case Intrinsic::masked_gather: 1002 return simplifyMaskedGather(*II, *this); 1003 case Intrinsic::masked_scatter: 1004 return simplifyMaskedScatter(*II, *this); 1005 1006 case Intrinsic::powi: 1007 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) { 1008 // powi(x, 0) -> 1.0 1009 if (Power->isZero()) 1010 return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0)); 1011 // powi(x, 1) -> x 1012 if (Power->isOne()) 1013 return replaceInstUsesWith(CI, II->getArgOperand(0)); 1014 // powi(x, -1) -> 1/x 1015 if (Power->isAllOnesValue()) 1016 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0), 1017 II->getArgOperand(0)); 1018 } 1019 break; 1020 case Intrinsic::cttz: { 1021 // If all bits below the first known one are known zero, 1022 // this value is constant. 1023 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType()); 1024 // FIXME: Try to simplify vectors of integers. 1025 if (!IT) break; 1026 uint32_t BitWidth = IT->getBitWidth(); 1027 APInt KnownZero(BitWidth, 0); 1028 APInt KnownOne(BitWidth, 0); 1029 computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II); 1030 unsigned TrailingZeros = KnownOne.countTrailingZeros(); 1031 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros)); 1032 if ((Mask & KnownZero) == Mask) 1033 return replaceInstUsesWith(CI, ConstantInt::get(IT, 1034 APInt(BitWidth, TrailingZeros))); 1035 1036 } 1037 break; 1038 case Intrinsic::ctlz: { 1039 // If all bits above the first known one are known zero, 1040 // this value is constant. 1041 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType()); 1042 // FIXME: Try to simplify vectors of integers. 1043 if (!IT) break; 1044 uint32_t BitWidth = IT->getBitWidth(); 1045 APInt KnownZero(BitWidth, 0); 1046 APInt KnownOne(BitWidth, 0); 1047 computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II); 1048 unsigned LeadingZeros = KnownOne.countLeadingZeros(); 1049 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros)); 1050 if ((Mask & KnownZero) == Mask) 1051 return replaceInstUsesWith(CI, ConstantInt::get(IT, 1052 APInt(BitWidth, LeadingZeros))); 1053 1054 } 1055 break; 1056 1057 case Intrinsic::uadd_with_overflow: 1058 case Intrinsic::sadd_with_overflow: 1059 case Intrinsic::umul_with_overflow: 1060 case Intrinsic::smul_with_overflow: 1061 if (isa<Constant>(II->getArgOperand(0)) && 1062 !isa<Constant>(II->getArgOperand(1))) { 1063 // Canonicalize constants into the RHS. 1064 Value *LHS = II->getArgOperand(0); 1065 II->setArgOperand(0, II->getArgOperand(1)); 1066 II->setArgOperand(1, LHS); 1067 return II; 1068 } 1069 // fall through 1070 1071 case Intrinsic::usub_with_overflow: 1072 case Intrinsic::ssub_with_overflow: { 1073 OverflowCheckFlavor OCF = 1074 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID()); 1075 assert(OCF != OCF_INVALID && "unexpected!"); 1076 1077 Value *OperationResult = nullptr; 1078 Constant *OverflowResult = nullptr; 1079 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1), 1080 *II, OperationResult, OverflowResult)) 1081 return CreateOverflowTuple(II, OperationResult, OverflowResult); 1082 1083 break; 1084 } 1085 1086 case Intrinsic::minnum: 1087 case Intrinsic::maxnum: { 1088 Value *Arg0 = II->getArgOperand(0); 1089 Value *Arg1 = II->getArgOperand(1); 1090 // Canonicalize constants to the RHS. 1091 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) { 1092 II->setArgOperand(0, Arg1); 1093 II->setArgOperand(1, Arg0); 1094 return II; 1095 } 1096 if (Value *V = simplifyMinnumMaxnum(*II)) 1097 return replaceInstUsesWith(*II, V); 1098 break; 1099 } 1100 case Intrinsic::ppc_altivec_lvx: 1101 case Intrinsic::ppc_altivec_lvxl: 1102 // Turn PPC lvx -> load if the pointer is known aligned. 1103 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >= 1104 16) { 1105 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), 1106 PointerType::getUnqual(II->getType())); 1107 return new LoadInst(Ptr); 1108 } 1109 break; 1110 case Intrinsic::ppc_vsx_lxvw4x: 1111 case Intrinsic::ppc_vsx_lxvd2x: { 1112 // Turn PPC VSX loads into normal loads. 1113 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), 1114 PointerType::getUnqual(II->getType())); 1115 return new LoadInst(Ptr, Twine(""), false, 1); 1116 } 1117 case Intrinsic::ppc_altivec_stvx: 1118 case Intrinsic::ppc_altivec_stvxl: 1119 // Turn stvx -> store if the pointer is known aligned. 1120 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, AC, DT) >= 1121 16) { 1122 Type *OpPtrTy = 1123 PointerType::getUnqual(II->getArgOperand(0)->getType()); 1124 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy); 1125 return new StoreInst(II->getArgOperand(0), Ptr); 1126 } 1127 break; 1128 case Intrinsic::ppc_vsx_stxvw4x: 1129 case Intrinsic::ppc_vsx_stxvd2x: { 1130 // Turn PPC VSX stores into normal stores. 1131 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType()); 1132 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy); 1133 return new StoreInst(II->getArgOperand(0), Ptr, false, 1); 1134 } 1135 case Intrinsic::ppc_qpx_qvlfs: 1136 // Turn PPC QPX qvlfs -> load if the pointer is known aligned. 1137 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >= 1138 16) { 1139 Type *VTy = VectorType::get(Builder->getFloatTy(), 1140 II->getType()->getVectorNumElements()); 1141 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), 1142 PointerType::getUnqual(VTy)); 1143 Value *Load = Builder->CreateLoad(Ptr); 1144 return new FPExtInst(Load, II->getType()); 1145 } 1146 break; 1147 case Intrinsic::ppc_qpx_qvlfd: 1148 // Turn PPC QPX qvlfd -> load if the pointer is known aligned. 1149 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, AC, DT) >= 1150 32) { 1151 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), 1152 PointerType::getUnqual(II->getType())); 1153 return new LoadInst(Ptr); 1154 } 1155 break; 1156 case Intrinsic::ppc_qpx_qvstfs: 1157 // Turn PPC QPX qvstfs -> store if the pointer is known aligned. 1158 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, AC, DT) >= 1159 16) { 1160 Type *VTy = VectorType::get(Builder->getFloatTy(), 1161 II->getArgOperand(0)->getType()->getVectorNumElements()); 1162 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy); 1163 Type *OpPtrTy = PointerType::getUnqual(VTy); 1164 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy); 1165 return new StoreInst(TOp, Ptr); 1166 } 1167 break; 1168 case Intrinsic::ppc_qpx_qvstfd: 1169 // Turn PPC QPX qvstfd -> store if the pointer is known aligned. 1170 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, AC, DT) >= 1171 32) { 1172 Type *OpPtrTy = 1173 PointerType::getUnqual(II->getArgOperand(0)->getType()); 1174 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy); 1175 return new StoreInst(II->getArgOperand(0), Ptr); 1176 } 1177 break; 1178 1179 case Intrinsic::x86_sse_storeu_ps: 1180 case Intrinsic::x86_sse2_storeu_pd: 1181 case Intrinsic::x86_sse2_storeu_dq: 1182 // Turn X86 storeu -> store if the pointer is known aligned. 1183 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >= 1184 16) { 1185 Type *OpPtrTy = 1186 PointerType::getUnqual(II->getArgOperand(1)->getType()); 1187 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy); 1188 return new StoreInst(II->getArgOperand(1), Ptr); 1189 } 1190 break; 1191 1192 case Intrinsic::x86_vcvtph2ps_128: 1193 case Intrinsic::x86_vcvtph2ps_256: { 1194 auto Arg = II->getArgOperand(0); 1195 auto ArgType = cast<VectorType>(Arg->getType()); 1196 auto RetType = cast<VectorType>(II->getType()); 1197 unsigned ArgWidth = ArgType->getNumElements(); 1198 unsigned RetWidth = RetType->getNumElements(); 1199 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths"); 1200 assert(ArgType->isIntOrIntVectorTy() && 1201 ArgType->getScalarSizeInBits() == 16 && 1202 "CVTPH2PS input type should be 16-bit integer vector"); 1203 assert(RetType->getScalarType()->isFloatTy() && 1204 "CVTPH2PS output type should be 32-bit float vector"); 1205 1206 // Constant folding: Convert to generic half to single conversion. 1207 if (isa<ConstantAggregateZero>(Arg)) 1208 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType)); 1209 1210 if (isa<ConstantDataVector>(Arg)) { 1211 auto VectorHalfAsShorts = Arg; 1212 if (RetWidth < ArgWidth) { 1213 SmallVector<int, 8> SubVecMask; 1214 for (unsigned i = 0; i != RetWidth; ++i) 1215 SubVecMask.push_back((int)i); 1216 VectorHalfAsShorts = Builder->CreateShuffleVector( 1217 Arg, UndefValue::get(ArgType), SubVecMask); 1218 } 1219 1220 auto VectorHalfType = 1221 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth); 1222 auto VectorHalfs = 1223 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType); 1224 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType); 1225 return replaceInstUsesWith(*II, VectorFloats); 1226 } 1227 1228 // We only use the lowest lanes of the argument. 1229 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) { 1230 II->setArgOperand(0, V); 1231 return II; 1232 } 1233 break; 1234 } 1235 1236 case Intrinsic::x86_sse_cvtss2si: 1237 case Intrinsic::x86_sse_cvtss2si64: 1238 case Intrinsic::x86_sse_cvttss2si: 1239 case Intrinsic::x86_sse_cvttss2si64: 1240 case Intrinsic::x86_sse2_cvtsd2si: 1241 case Intrinsic::x86_sse2_cvtsd2si64: 1242 case Intrinsic::x86_sse2_cvttsd2si: 1243 case Intrinsic::x86_sse2_cvttsd2si64: { 1244 // These intrinsics only demand the 0th element of their input vectors. If 1245 // we can simplify the input based on that, do so now. 1246 Value *Arg = II->getArgOperand(0); 1247 unsigned VWidth = Arg->getType()->getVectorNumElements(); 1248 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) { 1249 II->setArgOperand(0, V); 1250 return II; 1251 } 1252 break; 1253 } 1254 1255 case Intrinsic::x86_sse_comieq_ss: 1256 case Intrinsic::x86_sse_comige_ss: 1257 case Intrinsic::x86_sse_comigt_ss: 1258 case Intrinsic::x86_sse_comile_ss: 1259 case Intrinsic::x86_sse_comilt_ss: 1260 case Intrinsic::x86_sse_comineq_ss: 1261 case Intrinsic::x86_sse_ucomieq_ss: 1262 case Intrinsic::x86_sse_ucomige_ss: 1263 case Intrinsic::x86_sse_ucomigt_ss: 1264 case Intrinsic::x86_sse_ucomile_ss: 1265 case Intrinsic::x86_sse_ucomilt_ss: 1266 case Intrinsic::x86_sse_ucomineq_ss: 1267 case Intrinsic::x86_sse2_comieq_sd: 1268 case Intrinsic::x86_sse2_comige_sd: 1269 case Intrinsic::x86_sse2_comigt_sd: 1270 case Intrinsic::x86_sse2_comile_sd: 1271 case Intrinsic::x86_sse2_comilt_sd: 1272 case Intrinsic::x86_sse2_comineq_sd: 1273 case Intrinsic::x86_sse2_ucomieq_sd: 1274 case Intrinsic::x86_sse2_ucomige_sd: 1275 case Intrinsic::x86_sse2_ucomigt_sd: 1276 case Intrinsic::x86_sse2_ucomile_sd: 1277 case Intrinsic::x86_sse2_ucomilt_sd: 1278 case Intrinsic::x86_sse2_ucomineq_sd: { 1279 // These intrinsics only demand the 0th element of their input vectors. If 1280 // we can simplify the input based on that, do so now. 1281 Value *Arg0 = II->getArgOperand(0); 1282 Value *Arg1 = II->getArgOperand(1); 1283 unsigned VWidth = Arg0->getType()->getVectorNumElements(); 1284 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) { 1285 II->setArgOperand(0, V); 1286 return II; 1287 } 1288 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) { 1289 II->setArgOperand(1, V); 1290 return II; 1291 } 1292 break; 1293 } 1294 1295 // Constant fold ashr( <A x Bi>, Ci ). 1296 // Constant fold lshr( <A x Bi>, Ci ). 1297 // Constant fold shl( <A x Bi>, Ci ). 1298 case Intrinsic::x86_sse2_psrai_d: 1299 case Intrinsic::x86_sse2_psrai_w: 1300 case Intrinsic::x86_avx2_psrai_d: 1301 case Intrinsic::x86_avx2_psrai_w: 1302 case Intrinsic::x86_sse2_psrli_d: 1303 case Intrinsic::x86_sse2_psrli_q: 1304 case Intrinsic::x86_sse2_psrli_w: 1305 case Intrinsic::x86_avx2_psrli_d: 1306 case Intrinsic::x86_avx2_psrli_q: 1307 case Intrinsic::x86_avx2_psrli_w: 1308 case Intrinsic::x86_sse2_pslli_d: 1309 case Intrinsic::x86_sse2_pslli_q: 1310 case Intrinsic::x86_sse2_pslli_w: 1311 case Intrinsic::x86_avx2_pslli_d: 1312 case Intrinsic::x86_avx2_pslli_q: 1313 case Intrinsic::x86_avx2_pslli_w: 1314 if (Value *V = simplifyX86immShift(*II, *Builder)) 1315 return replaceInstUsesWith(*II, V); 1316 break; 1317 1318 case Intrinsic::x86_sse2_psra_d: 1319 case Intrinsic::x86_sse2_psra_w: 1320 case Intrinsic::x86_avx2_psra_d: 1321 case Intrinsic::x86_avx2_psra_w: 1322 case Intrinsic::x86_sse2_psrl_d: 1323 case Intrinsic::x86_sse2_psrl_q: 1324 case Intrinsic::x86_sse2_psrl_w: 1325 case Intrinsic::x86_avx2_psrl_d: 1326 case Intrinsic::x86_avx2_psrl_q: 1327 case Intrinsic::x86_avx2_psrl_w: 1328 case Intrinsic::x86_sse2_psll_d: 1329 case Intrinsic::x86_sse2_psll_q: 1330 case Intrinsic::x86_sse2_psll_w: 1331 case Intrinsic::x86_avx2_psll_d: 1332 case Intrinsic::x86_avx2_psll_q: 1333 case Intrinsic::x86_avx2_psll_w: { 1334 if (Value *V = simplifyX86immShift(*II, *Builder)) 1335 return replaceInstUsesWith(*II, V); 1336 1337 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector 1338 // operand to compute the shift amount. 1339 Value *Arg1 = II->getArgOperand(1); 1340 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 && 1341 "Unexpected packed shift size"); 1342 unsigned VWidth = Arg1->getType()->getVectorNumElements(); 1343 1344 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) { 1345 II->setArgOperand(1, V); 1346 return II; 1347 } 1348 break; 1349 } 1350 1351 case Intrinsic::x86_avx2_pmovsxbd: 1352 case Intrinsic::x86_avx2_pmovsxbq: 1353 case Intrinsic::x86_avx2_pmovsxbw: 1354 case Intrinsic::x86_avx2_pmovsxdq: 1355 case Intrinsic::x86_avx2_pmovsxwd: 1356 case Intrinsic::x86_avx2_pmovsxwq: 1357 if (Value *V = simplifyX86extend(*II, *Builder, true)) 1358 return replaceInstUsesWith(*II, V); 1359 break; 1360 1361 case Intrinsic::x86_sse41_pmovzxbd: 1362 case Intrinsic::x86_sse41_pmovzxbq: 1363 case Intrinsic::x86_sse41_pmovzxbw: 1364 case Intrinsic::x86_sse41_pmovzxdq: 1365 case Intrinsic::x86_sse41_pmovzxwd: 1366 case Intrinsic::x86_sse41_pmovzxwq: 1367 case Intrinsic::x86_avx2_pmovzxbd: 1368 case Intrinsic::x86_avx2_pmovzxbq: 1369 case Intrinsic::x86_avx2_pmovzxbw: 1370 case Intrinsic::x86_avx2_pmovzxdq: 1371 case Intrinsic::x86_avx2_pmovzxwd: 1372 case Intrinsic::x86_avx2_pmovzxwq: 1373 if (Value *V = simplifyX86extend(*II, *Builder, false)) 1374 return replaceInstUsesWith(*II, V); 1375 break; 1376 1377 case Intrinsic::x86_sse41_insertps: 1378 if (Value *V = simplifyX86insertps(*II, *Builder)) 1379 return replaceInstUsesWith(*II, V); 1380 break; 1381 1382 case Intrinsic::x86_sse4a_extrq: { 1383 Value *Op0 = II->getArgOperand(0); 1384 Value *Op1 = II->getArgOperand(1); 1385 unsigned VWidth0 = Op0->getType()->getVectorNumElements(); 1386 unsigned VWidth1 = Op1->getType()->getVectorNumElements(); 1387 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && 1388 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 && 1389 VWidth1 == 16 && "Unexpected operand sizes"); 1390 1391 // See if we're dealing with constant values. 1392 Constant *C1 = dyn_cast<Constant>(Op1); 1393 ConstantInt *CILength = 1394 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0)) 1395 : nullptr; 1396 ConstantInt *CIIndex = 1397 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1)) 1398 : nullptr; 1399 1400 // Attempt to simplify to a constant, shuffle vector or EXTRQI call. 1401 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder)) 1402 return replaceInstUsesWith(*II, V); 1403 1404 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector 1405 // operands and the lowest 16-bits of the second. 1406 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) { 1407 II->setArgOperand(0, V); 1408 return II; 1409 } 1410 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) { 1411 II->setArgOperand(1, V); 1412 return II; 1413 } 1414 break; 1415 } 1416 1417 case Intrinsic::x86_sse4a_extrqi: { 1418 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining 1419 // bits of the lower 64-bits. The upper 64-bits are undefined. 1420 Value *Op0 = II->getArgOperand(0); 1421 unsigned VWidth = Op0->getType()->getVectorNumElements(); 1422 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 && 1423 "Unexpected operand size"); 1424 1425 // See if we're dealing with constant values. 1426 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1)); 1427 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2)); 1428 1429 // Attempt to simplify to a constant or shuffle vector. 1430 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder)) 1431 return replaceInstUsesWith(*II, V); 1432 1433 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector 1434 // operand. 1435 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) { 1436 II->setArgOperand(0, V); 1437 return II; 1438 } 1439 break; 1440 } 1441 1442 case Intrinsic::x86_sse4a_insertq: { 1443 Value *Op0 = II->getArgOperand(0); 1444 Value *Op1 = II->getArgOperand(1); 1445 unsigned VWidth = Op0->getType()->getVectorNumElements(); 1446 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && 1447 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 && 1448 Op1->getType()->getVectorNumElements() == 2 && 1449 "Unexpected operand size"); 1450 1451 // See if we're dealing with constant values. 1452 Constant *C1 = dyn_cast<Constant>(Op1); 1453 ConstantInt *CI11 = 1454 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1)) 1455 : nullptr; 1456 1457 // Attempt to simplify to a constant, shuffle vector or INSERTQI call. 1458 if (CI11) { 1459 APInt V11 = CI11->getValue(); 1460 APInt Len = V11.zextOrTrunc(6); 1461 APInt Idx = V11.lshr(8).zextOrTrunc(6); 1462 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder)) 1463 return replaceInstUsesWith(*II, V); 1464 } 1465 1466 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector 1467 // operand. 1468 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) { 1469 II->setArgOperand(0, V); 1470 return II; 1471 } 1472 break; 1473 } 1474 1475 case Intrinsic::x86_sse4a_insertqi: { 1476 // INSERTQI: Extract lowest Length bits from lower half of second source and 1477 // insert over first source starting at Index bit. The upper 64-bits are 1478 // undefined. 1479 Value *Op0 = II->getArgOperand(0); 1480 Value *Op1 = II->getArgOperand(1); 1481 unsigned VWidth0 = Op0->getType()->getVectorNumElements(); 1482 unsigned VWidth1 = Op1->getType()->getVectorNumElements(); 1483 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && 1484 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 && 1485 VWidth1 == 2 && "Unexpected operand sizes"); 1486 1487 // See if we're dealing with constant values. 1488 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2)); 1489 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3)); 1490 1491 // Attempt to simplify to a constant or shuffle vector. 1492 if (CILength && CIIndex) { 1493 APInt Len = CILength->getValue().zextOrTrunc(6); 1494 APInt Idx = CIIndex->getValue().zextOrTrunc(6); 1495 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder)) 1496 return replaceInstUsesWith(*II, V); 1497 } 1498 1499 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector 1500 // operands. 1501 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) { 1502 II->setArgOperand(0, V); 1503 return II; 1504 } 1505 1506 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) { 1507 II->setArgOperand(1, V); 1508 return II; 1509 } 1510 break; 1511 } 1512 1513 case Intrinsic::x86_sse41_pblendvb: 1514 case Intrinsic::x86_sse41_blendvps: 1515 case Intrinsic::x86_sse41_blendvpd: 1516 case Intrinsic::x86_avx_blendv_ps_256: 1517 case Intrinsic::x86_avx_blendv_pd_256: 1518 case Intrinsic::x86_avx2_pblendvb: { 1519 // Convert blendv* to vector selects if the mask is constant. 1520 // This optimization is convoluted because the intrinsic is defined as 1521 // getting a vector of floats or doubles for the ps and pd versions. 1522 // FIXME: That should be changed. 1523 1524 Value *Op0 = II->getArgOperand(0); 1525 Value *Op1 = II->getArgOperand(1); 1526 Value *Mask = II->getArgOperand(2); 1527 1528 // fold (blend A, A, Mask) -> A 1529 if (Op0 == Op1) 1530 return replaceInstUsesWith(CI, Op0); 1531 1532 // Zero Mask - select 1st argument. 1533 if (isa<ConstantAggregateZero>(Mask)) 1534 return replaceInstUsesWith(CI, Op0); 1535 1536 // Constant Mask - select 1st/2nd argument lane based on top bit of mask. 1537 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) { 1538 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask); 1539 return SelectInst::Create(NewSelector, Op1, Op0, "blendv"); 1540 } 1541 break; 1542 } 1543 1544 case Intrinsic::x86_ssse3_pshuf_b_128: 1545 case Intrinsic::x86_avx2_pshuf_b: { 1546 // Turn pshufb(V1,mask) -> shuffle(V1,Zero,mask) if mask is a constant. 1547 auto *V = II->getArgOperand(1); 1548 auto *VTy = cast<VectorType>(V->getType()); 1549 unsigned NumElts = VTy->getNumElements(); 1550 assert((NumElts == 16 || NumElts == 32) && 1551 "Unexpected number of elements in shuffle mask!"); 1552 // Initialize the resulting shuffle mask to all zeroes. 1553 uint32_t Indexes[32] = {0}; 1554 1555 if (auto *Mask = dyn_cast<ConstantDataVector>(V)) { 1556 // Each byte in the shuffle control mask forms an index to permute the 1557 // corresponding byte in the destination operand. 1558 for (unsigned I = 0; I < NumElts; ++I) { 1559 int8_t Index = Mask->getElementAsInteger(I); 1560 // If the most significant bit (bit[7]) of each byte of the shuffle 1561 // control mask is set, then zero is written in the result byte. 1562 // The zero vector is in the right-hand side of the resulting 1563 // shufflevector. 1564 1565 // The value of each index is the least significant 4 bits of the 1566 // shuffle control byte. 1567 Indexes[I] = (Index < 0) ? NumElts : Index & 0xF; 1568 } 1569 } else if (!isa<ConstantAggregateZero>(V)) 1570 break; 1571 1572 // The value of each index for the high 128-bit lane is the least 1573 // significant 4 bits of the respective shuffle control byte. 1574 for (unsigned I = 16; I < NumElts; ++I) 1575 Indexes[I] += I & 0xF0; 1576 1577 auto NewC = ConstantDataVector::get(V->getContext(), 1578 makeArrayRef(Indexes, NumElts)); 1579 auto V1 = II->getArgOperand(0); 1580 auto V2 = Constant::getNullValue(II->getType()); 1581 auto Shuffle = Builder->CreateShuffleVector(V1, V2, NewC); 1582 return replaceInstUsesWith(CI, Shuffle); 1583 } 1584 1585 case Intrinsic::x86_avx_vpermilvar_ps: 1586 case Intrinsic::x86_avx_vpermilvar_ps_256: 1587 case Intrinsic::x86_avx_vpermilvar_pd: 1588 case Intrinsic::x86_avx_vpermilvar_pd_256: { 1589 // Convert vpermil* to shufflevector if the mask is constant. 1590 Value *V = II->getArgOperand(1); 1591 unsigned Size = cast<VectorType>(V->getType())->getNumElements(); 1592 assert(Size == 8 || Size == 4 || Size == 2); 1593 uint32_t Indexes[8]; 1594 if (auto C = dyn_cast<ConstantDataVector>(V)) { 1595 // The intrinsics only read one or two bits, clear the rest. 1596 for (unsigned I = 0; I < Size; ++I) { 1597 uint32_t Index = C->getElementAsInteger(I) & 0x3; 1598 if (II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd || 1599 II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) 1600 Index >>= 1; 1601 Indexes[I] = Index; 1602 } 1603 } else if (isa<ConstantAggregateZero>(V)) { 1604 for (unsigned I = 0; I < Size; ++I) 1605 Indexes[I] = 0; 1606 } else { 1607 break; 1608 } 1609 // The _256 variants are a bit trickier since the mask bits always index 1610 // into the corresponding 128 half. In order to convert to a generic 1611 // shuffle, we have to make that explicit. 1612 if (II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 || 1613 II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) { 1614 for (unsigned I = Size / 2; I < Size; ++I) 1615 Indexes[I] += Size / 2; 1616 } 1617 auto NewC = 1618 ConstantDataVector::get(V->getContext(), makeArrayRef(Indexes, Size)); 1619 auto V1 = II->getArgOperand(0); 1620 auto V2 = UndefValue::get(V1->getType()); 1621 auto Shuffle = Builder->CreateShuffleVector(V1, V2, NewC); 1622 return replaceInstUsesWith(CI, Shuffle); 1623 } 1624 1625 case Intrinsic::x86_avx_vperm2f128_pd_256: 1626 case Intrinsic::x86_avx_vperm2f128_ps_256: 1627 case Intrinsic::x86_avx_vperm2f128_si_256: 1628 case Intrinsic::x86_avx2_vperm2i128: 1629 if (Value *V = simplifyX86vperm2(*II, *Builder)) 1630 return replaceInstUsesWith(*II, V); 1631 break; 1632 1633 case Intrinsic::x86_avx_maskstore_ps: 1634 case Intrinsic::x86_avx_maskstore_pd: 1635 case Intrinsic::x86_avx_maskstore_ps_256: 1636 case Intrinsic::x86_avx_maskstore_pd_256: 1637 case Intrinsic::x86_avx2_maskstore_d: 1638 case Intrinsic::x86_avx2_maskstore_q: 1639 case Intrinsic::x86_avx2_maskstore_d_256: 1640 case Intrinsic::x86_avx2_maskstore_q_256: 1641 if (simplifyX86MaskedStore(*II, *this)) 1642 return nullptr; 1643 break; 1644 1645 case Intrinsic::x86_xop_vpcomb: 1646 case Intrinsic::x86_xop_vpcomd: 1647 case Intrinsic::x86_xop_vpcomq: 1648 case Intrinsic::x86_xop_vpcomw: 1649 if (Value *V = simplifyX86vpcom(*II, *Builder, true)) 1650 return replaceInstUsesWith(*II, V); 1651 break; 1652 1653 case Intrinsic::x86_xop_vpcomub: 1654 case Intrinsic::x86_xop_vpcomud: 1655 case Intrinsic::x86_xop_vpcomuq: 1656 case Intrinsic::x86_xop_vpcomuw: 1657 if (Value *V = simplifyX86vpcom(*II, *Builder, false)) 1658 return replaceInstUsesWith(*II, V); 1659 break; 1660 1661 case Intrinsic::ppc_altivec_vperm: 1662 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant. 1663 // Note that ppc_altivec_vperm has a big-endian bias, so when creating 1664 // a vectorshuffle for little endian, we must undo the transformation 1665 // performed on vec_perm in altivec.h. That is, we must complement 1666 // the permutation mask with respect to 31 and reverse the order of 1667 // V1 and V2. 1668 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) { 1669 assert(Mask->getType()->getVectorNumElements() == 16 && 1670 "Bad type for intrinsic!"); 1671 1672 // Check that all of the elements are integer constants or undefs. 1673 bool AllEltsOk = true; 1674 for (unsigned i = 0; i != 16; ++i) { 1675 Constant *Elt = Mask->getAggregateElement(i); 1676 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) { 1677 AllEltsOk = false; 1678 break; 1679 } 1680 } 1681 1682 if (AllEltsOk) { 1683 // Cast the input vectors to byte vectors. 1684 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0), 1685 Mask->getType()); 1686 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1), 1687 Mask->getType()); 1688 Value *Result = UndefValue::get(Op0->getType()); 1689 1690 // Only extract each element once. 1691 Value *ExtractedElts[32]; 1692 memset(ExtractedElts, 0, sizeof(ExtractedElts)); 1693 1694 for (unsigned i = 0; i != 16; ++i) { 1695 if (isa<UndefValue>(Mask->getAggregateElement(i))) 1696 continue; 1697 unsigned Idx = 1698 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue(); 1699 Idx &= 31; // Match the hardware behavior. 1700 if (DL.isLittleEndian()) 1701 Idx = 31 - Idx; 1702 1703 if (!ExtractedElts[Idx]) { 1704 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0; 1705 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1; 1706 ExtractedElts[Idx] = 1707 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse, 1708 Builder->getInt32(Idx&15)); 1709 } 1710 1711 // Insert this value into the result vector. 1712 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx], 1713 Builder->getInt32(i)); 1714 } 1715 return CastInst::Create(Instruction::BitCast, Result, CI.getType()); 1716 } 1717 } 1718 break; 1719 1720 case Intrinsic::arm_neon_vld1: 1721 case Intrinsic::arm_neon_vld2: 1722 case Intrinsic::arm_neon_vld3: 1723 case Intrinsic::arm_neon_vld4: 1724 case Intrinsic::arm_neon_vld2lane: 1725 case Intrinsic::arm_neon_vld3lane: 1726 case Intrinsic::arm_neon_vld4lane: 1727 case Intrinsic::arm_neon_vst1: 1728 case Intrinsic::arm_neon_vst2: 1729 case Intrinsic::arm_neon_vst3: 1730 case Intrinsic::arm_neon_vst4: 1731 case Intrinsic::arm_neon_vst2lane: 1732 case Intrinsic::arm_neon_vst3lane: 1733 case Intrinsic::arm_neon_vst4lane: { 1734 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL, II, AC, DT); 1735 unsigned AlignArg = II->getNumArgOperands() - 1; 1736 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg)); 1737 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) { 1738 II->setArgOperand(AlignArg, 1739 ConstantInt::get(Type::getInt32Ty(II->getContext()), 1740 MemAlign, false)); 1741 return II; 1742 } 1743 break; 1744 } 1745 1746 case Intrinsic::arm_neon_vmulls: 1747 case Intrinsic::arm_neon_vmullu: 1748 case Intrinsic::aarch64_neon_smull: 1749 case Intrinsic::aarch64_neon_umull: { 1750 Value *Arg0 = II->getArgOperand(0); 1751 Value *Arg1 = II->getArgOperand(1); 1752 1753 // Handle mul by zero first: 1754 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) { 1755 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType())); 1756 } 1757 1758 // Check for constant LHS & RHS - in this case we just simplify. 1759 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu || 1760 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull); 1761 VectorType *NewVT = cast<VectorType>(II->getType()); 1762 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) { 1763 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) { 1764 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext); 1765 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext); 1766 1767 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1)); 1768 } 1769 1770 // Couldn't simplify - canonicalize constant to the RHS. 1771 std::swap(Arg0, Arg1); 1772 } 1773 1774 // Handle mul by one: 1775 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) 1776 if (ConstantInt *Splat = 1777 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue())) 1778 if (Splat->isOne()) 1779 return CastInst::CreateIntegerCast(Arg0, II->getType(), 1780 /*isSigned=*/!Zext); 1781 1782 break; 1783 } 1784 1785 case Intrinsic::amdgcn_rcp: { 1786 if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) { 1787 const APFloat &ArgVal = C->getValueAPF(); 1788 APFloat Val(ArgVal.getSemantics(), 1.0); 1789 APFloat::opStatus Status = Val.divide(ArgVal, 1790 APFloat::rmNearestTiesToEven); 1791 // Only do this if it was exact and therefore not dependent on the 1792 // rounding mode. 1793 if (Status == APFloat::opOK) 1794 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val)); 1795 } 1796 1797 break; 1798 } 1799 case Intrinsic::stackrestore: { 1800 // If the save is right next to the restore, remove the restore. This can 1801 // happen when variable allocas are DCE'd. 1802 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) { 1803 if (SS->getIntrinsicID() == Intrinsic::stacksave) { 1804 if (&*++SS->getIterator() == II) 1805 return eraseInstFromFunction(CI); 1806 } 1807 } 1808 1809 // Scan down this block to see if there is another stack restore in the 1810 // same block without an intervening call/alloca. 1811 BasicBlock::iterator BI(II); 1812 TerminatorInst *TI = II->getParent()->getTerminator(); 1813 bool CannotRemove = false; 1814 for (++BI; &*BI != TI; ++BI) { 1815 if (isa<AllocaInst>(BI)) { 1816 CannotRemove = true; 1817 break; 1818 } 1819 if (CallInst *BCI = dyn_cast<CallInst>(BI)) { 1820 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) { 1821 // If there is a stackrestore below this one, remove this one. 1822 if (II->getIntrinsicID() == Intrinsic::stackrestore) 1823 return eraseInstFromFunction(CI); 1824 1825 // Bail if we cross over an intrinsic with side effects, such as 1826 // llvm.stacksave, llvm.read_register, or llvm.setjmp. 1827 if (II->mayHaveSideEffects()) { 1828 CannotRemove = true; 1829 break; 1830 } 1831 } else { 1832 // If we found a non-intrinsic call, we can't remove the stack 1833 // restore. 1834 CannotRemove = true; 1835 break; 1836 } 1837 } 1838 } 1839 1840 // If the stack restore is in a return, resume, or unwind block and if there 1841 // are no allocas or calls between the restore and the return, nuke the 1842 // restore. 1843 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI))) 1844 return eraseInstFromFunction(CI); 1845 break; 1846 } 1847 case Intrinsic::lifetime_start: { 1848 // Remove trivially empty lifetime_start/end ranges, i.e. a start 1849 // immediately followed by an end (ignoring debuginfo or other 1850 // lifetime markers in between). 1851 BasicBlock::iterator BI = II->getIterator(), BE = II->getParent()->end(); 1852 for (++BI; BI != BE; ++BI) { 1853 if (IntrinsicInst *LTE = dyn_cast<IntrinsicInst>(BI)) { 1854 if (isa<DbgInfoIntrinsic>(LTE) || 1855 LTE->getIntrinsicID() == Intrinsic::lifetime_start) 1856 continue; 1857 if (LTE->getIntrinsicID() == Intrinsic::lifetime_end) { 1858 if (II->getOperand(0) == LTE->getOperand(0) && 1859 II->getOperand(1) == LTE->getOperand(1)) { 1860 eraseInstFromFunction(*LTE); 1861 return eraseInstFromFunction(*II); 1862 } 1863 continue; 1864 } 1865 } 1866 break; 1867 } 1868 break; 1869 } 1870 case Intrinsic::assume: { 1871 // Canonicalize assume(a && b) -> assume(a); assume(b); 1872 // Note: New assumption intrinsics created here are registered by 1873 // the InstCombineIRInserter object. 1874 Value *IIOperand = II->getArgOperand(0), *A, *B, 1875 *AssumeIntrinsic = II->getCalledValue(); 1876 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) { 1877 Builder->CreateCall(AssumeIntrinsic, A, II->getName()); 1878 Builder->CreateCall(AssumeIntrinsic, B, II->getName()); 1879 return eraseInstFromFunction(*II); 1880 } 1881 // assume(!(a || b)) -> assume(!a); assume(!b); 1882 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) { 1883 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A), 1884 II->getName()); 1885 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B), 1886 II->getName()); 1887 return eraseInstFromFunction(*II); 1888 } 1889 1890 // assume( (load addr) != null ) -> add 'nonnull' metadata to load 1891 // (if assume is valid at the load) 1892 if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) { 1893 Value *LHS = ICmp->getOperand(0); 1894 Value *RHS = ICmp->getOperand(1); 1895 if (ICmpInst::ICMP_NE == ICmp->getPredicate() && 1896 isa<LoadInst>(LHS) && 1897 isa<Constant>(RHS) && 1898 RHS->getType()->isPointerTy() && 1899 cast<Constant>(RHS)->isNullValue()) { 1900 LoadInst* LI = cast<LoadInst>(LHS); 1901 if (isValidAssumeForContext(II, LI, DT)) { 1902 MDNode *MD = MDNode::get(II->getContext(), None); 1903 LI->setMetadata(LLVMContext::MD_nonnull, MD); 1904 return eraseInstFromFunction(*II); 1905 } 1906 } 1907 // TODO: apply nonnull return attributes to calls and invokes 1908 // TODO: apply range metadata for range check patterns? 1909 } 1910 // If there is a dominating assume with the same condition as this one, 1911 // then this one is redundant, and should be removed. 1912 APInt KnownZero(1, 0), KnownOne(1, 0); 1913 computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II); 1914 if (KnownOne.isAllOnesValue()) 1915 return eraseInstFromFunction(*II); 1916 1917 break; 1918 } 1919 case Intrinsic::experimental_gc_relocate: { 1920 // Translate facts known about a pointer before relocating into 1921 // facts about the relocate value, while being careful to 1922 // preserve relocation semantics. 1923 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr(); 1924 1925 // Remove the relocation if unused, note that this check is required 1926 // to prevent the cases below from looping forever. 1927 if (II->use_empty()) 1928 return eraseInstFromFunction(*II); 1929 1930 // Undef is undef, even after relocation. 1931 // TODO: provide a hook for this in GCStrategy. This is clearly legal for 1932 // most practical collectors, but there was discussion in the review thread 1933 // about whether it was legal for all possible collectors. 1934 if (isa<UndefValue>(DerivedPtr)) 1935 // Use undef of gc_relocate's type to replace it. 1936 return replaceInstUsesWith(*II, UndefValue::get(II->getType())); 1937 1938 if (auto *PT = dyn_cast<PointerType>(II->getType())) { 1939 // The relocation of null will be null for most any collector. 1940 // TODO: provide a hook for this in GCStrategy. There might be some 1941 // weird collector this property does not hold for. 1942 if (isa<ConstantPointerNull>(DerivedPtr)) 1943 // Use null-pointer of gc_relocate's type to replace it. 1944 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT)); 1945 1946 // isKnownNonNull -> nonnull attribute 1947 if (isKnownNonNullAt(DerivedPtr, II, DT, TLI)) 1948 II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull); 1949 } 1950 1951 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p)) 1952 // Canonicalize on the type from the uses to the defs 1953 1954 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...) 1955 break; 1956 } 1957 } 1958 1959 return visitCallSite(II); 1960 } 1961 1962 // InvokeInst simplification 1963 // 1964 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) { 1965 return visitCallSite(&II); 1966 } 1967 1968 /// If this cast does not affect the value passed through the varargs area, we 1969 /// can eliminate the use of the cast. 1970 static bool isSafeToEliminateVarargsCast(const CallSite CS, 1971 const DataLayout &DL, 1972 const CastInst *const CI, 1973 const int ix) { 1974 if (!CI->isLosslessCast()) 1975 return false; 1976 1977 // If this is a GC intrinsic, avoid munging types. We need types for 1978 // statepoint reconstruction in SelectionDAG. 1979 // TODO: This is probably something which should be expanded to all 1980 // intrinsics since the entire point of intrinsics is that 1981 // they are understandable by the optimizer. 1982 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) 1983 return false; 1984 1985 // The size of ByVal or InAlloca arguments is derived from the type, so we 1986 // can't change to a type with a different size. If the size were 1987 // passed explicitly we could avoid this check. 1988 if (!CS.isByValOrInAllocaArgument(ix)) 1989 return true; 1990 1991 Type* SrcTy = 1992 cast<PointerType>(CI->getOperand(0)->getType())->getElementType(); 1993 Type* DstTy = cast<PointerType>(CI->getType())->getElementType(); 1994 if (!SrcTy->isSized() || !DstTy->isSized()) 1995 return false; 1996 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy)) 1997 return false; 1998 return true; 1999 } 2000 2001 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) { 2002 if (!CI->getCalledFunction()) return nullptr; 2003 2004 auto InstCombineRAUW = [this](Instruction *From, Value *With) { 2005 replaceInstUsesWith(*From, With); 2006 }; 2007 LibCallSimplifier Simplifier(DL, TLI, InstCombineRAUW); 2008 if (Value *With = Simplifier.optimizeCall(CI)) { 2009 ++NumSimplified; 2010 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With); 2011 } 2012 2013 return nullptr; 2014 } 2015 2016 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) { 2017 // Strip off at most one level of pointer casts, looking for an alloca. This 2018 // is good enough in practice and simpler than handling any number of casts. 2019 Value *Underlying = TrampMem->stripPointerCasts(); 2020 if (Underlying != TrampMem && 2021 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem)) 2022 return nullptr; 2023 if (!isa<AllocaInst>(Underlying)) 2024 return nullptr; 2025 2026 IntrinsicInst *InitTrampoline = nullptr; 2027 for (User *U : TrampMem->users()) { 2028 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U); 2029 if (!II) 2030 return nullptr; 2031 if (II->getIntrinsicID() == Intrinsic::init_trampoline) { 2032 if (InitTrampoline) 2033 // More than one init_trampoline writes to this value. Give up. 2034 return nullptr; 2035 InitTrampoline = II; 2036 continue; 2037 } 2038 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline) 2039 // Allow any number of calls to adjust.trampoline. 2040 continue; 2041 return nullptr; 2042 } 2043 2044 // No call to init.trampoline found. 2045 if (!InitTrampoline) 2046 return nullptr; 2047 2048 // Check that the alloca is being used in the expected way. 2049 if (InitTrampoline->getOperand(0) != TrampMem) 2050 return nullptr; 2051 2052 return InitTrampoline; 2053 } 2054 2055 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp, 2056 Value *TrampMem) { 2057 // Visit all the previous instructions in the basic block, and try to find a 2058 // init.trampoline which has a direct path to the adjust.trampoline. 2059 for (BasicBlock::iterator I = AdjustTramp->getIterator(), 2060 E = AdjustTramp->getParent()->begin(); 2061 I != E;) { 2062 Instruction *Inst = &*--I; 2063 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 2064 if (II->getIntrinsicID() == Intrinsic::init_trampoline && 2065 II->getOperand(0) == TrampMem) 2066 return II; 2067 if (Inst->mayWriteToMemory()) 2068 return nullptr; 2069 } 2070 return nullptr; 2071 } 2072 2073 // Given a call to llvm.adjust.trampoline, find and return the corresponding 2074 // call to llvm.init.trampoline if the call to the trampoline can be optimized 2075 // to a direct call to a function. Otherwise return NULL. 2076 // 2077 static IntrinsicInst *findInitTrampoline(Value *Callee) { 2078 Callee = Callee->stripPointerCasts(); 2079 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee); 2080 if (!AdjustTramp || 2081 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline) 2082 return nullptr; 2083 2084 Value *TrampMem = AdjustTramp->getOperand(0); 2085 2086 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem)) 2087 return IT; 2088 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem)) 2089 return IT; 2090 return nullptr; 2091 } 2092 2093 /// Improvements for call and invoke instructions. 2094 Instruction *InstCombiner::visitCallSite(CallSite CS) { 2095 2096 if (isAllocLikeFn(CS.getInstruction(), TLI)) 2097 return visitAllocSite(*CS.getInstruction()); 2098 2099 bool Changed = false; 2100 2101 // Mark any parameters that are known to be non-null with the nonnull 2102 // attribute. This is helpful for inlining calls to functions with null 2103 // checks on their arguments. 2104 SmallVector<unsigned, 4> Indices; 2105 unsigned ArgNo = 0; 2106 2107 for (Value *V : CS.args()) { 2108 if (V->getType()->isPointerTy() && 2109 !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) && 2110 isKnownNonNullAt(V, CS.getInstruction(), DT, TLI)) 2111 Indices.push_back(ArgNo + 1); 2112 ArgNo++; 2113 } 2114 2115 assert(ArgNo == CS.arg_size() && "sanity check"); 2116 2117 if (!Indices.empty()) { 2118 AttributeSet AS = CS.getAttributes(); 2119 LLVMContext &Ctx = CS.getInstruction()->getContext(); 2120 AS = AS.addAttribute(Ctx, Indices, 2121 Attribute::get(Ctx, Attribute::NonNull)); 2122 CS.setAttributes(AS); 2123 Changed = true; 2124 } 2125 2126 // If the callee is a pointer to a function, attempt to move any casts to the 2127 // arguments of the call/invoke. 2128 Value *Callee = CS.getCalledValue(); 2129 if (!isa<Function>(Callee) && transformConstExprCastCall(CS)) 2130 return nullptr; 2131 2132 if (Function *CalleeF = dyn_cast<Function>(Callee)) 2133 // If the call and callee calling conventions don't match, this call must 2134 // be unreachable, as the call is undefined. 2135 if (CalleeF->getCallingConv() != CS.getCallingConv() && 2136 // Only do this for calls to a function with a body. A prototype may 2137 // not actually end up matching the implementation's calling conv for a 2138 // variety of reasons (e.g. it may be written in assembly). 2139 !CalleeF->isDeclaration()) { 2140 Instruction *OldCall = CS.getInstruction(); 2141 new StoreInst(ConstantInt::getTrue(Callee->getContext()), 2142 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())), 2143 OldCall); 2144 // If OldCall does not return void then replaceAllUsesWith undef. 2145 // This allows ValueHandlers and custom metadata to adjust itself. 2146 if (!OldCall->getType()->isVoidTy()) 2147 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType())); 2148 if (isa<CallInst>(OldCall)) 2149 return eraseInstFromFunction(*OldCall); 2150 2151 // We cannot remove an invoke, because it would change the CFG, just 2152 // change the callee to a null pointer. 2153 cast<InvokeInst>(OldCall)->setCalledFunction( 2154 Constant::getNullValue(CalleeF->getType())); 2155 return nullptr; 2156 } 2157 2158 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) { 2159 // If CS does not return void then replaceAllUsesWith undef. 2160 // This allows ValueHandlers and custom metadata to adjust itself. 2161 if (!CS.getInstruction()->getType()->isVoidTy()) 2162 replaceInstUsesWith(*CS.getInstruction(), 2163 UndefValue::get(CS.getInstruction()->getType())); 2164 2165 if (isa<InvokeInst>(CS.getInstruction())) { 2166 // Can't remove an invoke because we cannot change the CFG. 2167 return nullptr; 2168 } 2169 2170 // This instruction is not reachable, just remove it. We insert a store to 2171 // undef so that we know that this code is not reachable, despite the fact 2172 // that we can't modify the CFG here. 2173 new StoreInst(ConstantInt::getTrue(Callee->getContext()), 2174 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())), 2175 CS.getInstruction()); 2176 2177 return eraseInstFromFunction(*CS.getInstruction()); 2178 } 2179 2180 if (IntrinsicInst *II = findInitTrampoline(Callee)) 2181 return transformCallThroughTrampoline(CS, II); 2182 2183 PointerType *PTy = cast<PointerType>(Callee->getType()); 2184 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 2185 if (FTy->isVarArg()) { 2186 int ix = FTy->getNumParams(); 2187 // See if we can optimize any arguments passed through the varargs area of 2188 // the call. 2189 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(), 2190 E = CS.arg_end(); I != E; ++I, ++ix) { 2191 CastInst *CI = dyn_cast<CastInst>(*I); 2192 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) { 2193 *I = CI->getOperand(0); 2194 Changed = true; 2195 } 2196 } 2197 } 2198 2199 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) { 2200 // Inline asm calls cannot throw - mark them 'nounwind'. 2201 CS.setDoesNotThrow(); 2202 Changed = true; 2203 } 2204 2205 // Try to optimize the call if possible, we require DataLayout for most of 2206 // this. None of these calls are seen as possibly dead so go ahead and 2207 // delete the instruction now. 2208 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) { 2209 Instruction *I = tryOptimizeCall(CI); 2210 // If we changed something return the result, etc. Otherwise let 2211 // the fallthrough check. 2212 if (I) return eraseInstFromFunction(*I); 2213 } 2214 2215 return Changed ? CS.getInstruction() : nullptr; 2216 } 2217 2218 /// If the callee is a constexpr cast of a function, attempt to move the cast to 2219 /// the arguments of the call/invoke. 2220 bool InstCombiner::transformConstExprCastCall(CallSite CS) { 2221 Function *Callee = 2222 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts()); 2223 if (!Callee) 2224 return false; 2225 // The prototype of thunks are a lie, don't try to directly call such 2226 // functions. 2227 if (Callee->hasFnAttribute("thunk")) 2228 return false; 2229 Instruction *Caller = CS.getInstruction(); 2230 const AttributeSet &CallerPAL = CS.getAttributes(); 2231 2232 // Okay, this is a cast from a function to a different type. Unless doing so 2233 // would cause a type conversion of one of our arguments, change this call to 2234 // be a direct call with arguments casted to the appropriate types. 2235 // 2236 FunctionType *FT = Callee->getFunctionType(); 2237 Type *OldRetTy = Caller->getType(); 2238 Type *NewRetTy = FT->getReturnType(); 2239 2240 // Check to see if we are changing the return type... 2241 if (OldRetTy != NewRetTy) { 2242 2243 if (NewRetTy->isStructTy()) 2244 return false; // TODO: Handle multiple return values. 2245 2246 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) { 2247 if (Callee->isDeclaration()) 2248 return false; // Cannot transform this return value. 2249 2250 if (!Caller->use_empty() && 2251 // void -> non-void is handled specially 2252 !NewRetTy->isVoidTy()) 2253 return false; // Cannot transform this return value. 2254 } 2255 2256 if (!CallerPAL.isEmpty() && !Caller->use_empty()) { 2257 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex); 2258 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy))) 2259 return false; // Attribute not compatible with transformed value. 2260 } 2261 2262 // If the callsite is an invoke instruction, and the return value is used by 2263 // a PHI node in a successor, we cannot change the return type of the call 2264 // because there is no place to put the cast instruction (without breaking 2265 // the critical edge). Bail out in this case. 2266 if (!Caller->use_empty()) 2267 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) 2268 for (User *U : II->users()) 2269 if (PHINode *PN = dyn_cast<PHINode>(U)) 2270 if (PN->getParent() == II->getNormalDest() || 2271 PN->getParent() == II->getUnwindDest()) 2272 return false; 2273 } 2274 2275 unsigned NumActualArgs = CS.arg_size(); 2276 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs); 2277 2278 // Prevent us turning: 2279 // declare void @takes_i32_inalloca(i32* inalloca) 2280 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0) 2281 // 2282 // into: 2283 // call void @takes_i32_inalloca(i32* null) 2284 // 2285 // Similarly, avoid folding away bitcasts of byval calls. 2286 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) || 2287 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal)) 2288 return false; 2289 2290 CallSite::arg_iterator AI = CS.arg_begin(); 2291 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) { 2292 Type *ParamTy = FT->getParamType(i); 2293 Type *ActTy = (*AI)->getType(); 2294 2295 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL)) 2296 return false; // Cannot transform this parameter value. 2297 2298 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1). 2299 overlaps(AttributeFuncs::typeIncompatible(ParamTy))) 2300 return false; // Attribute not compatible with transformed value. 2301 2302 if (CS.isInAllocaArgument(i)) 2303 return false; // Cannot transform to and from inalloca. 2304 2305 // If the parameter is passed as a byval argument, then we have to have a 2306 // sized type and the sized type has to have the same size as the old type. 2307 if (ParamTy != ActTy && 2308 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1, 2309 Attribute::ByVal)) { 2310 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy); 2311 if (!ParamPTy || !ParamPTy->getElementType()->isSized()) 2312 return false; 2313 2314 Type *CurElTy = ActTy->getPointerElementType(); 2315 if (DL.getTypeAllocSize(CurElTy) != 2316 DL.getTypeAllocSize(ParamPTy->getElementType())) 2317 return false; 2318 } 2319 } 2320 2321 if (Callee->isDeclaration()) { 2322 // Do not delete arguments unless we have a function body. 2323 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg()) 2324 return false; 2325 2326 // If the callee is just a declaration, don't change the varargsness of the 2327 // call. We don't want to introduce a varargs call where one doesn't 2328 // already exist. 2329 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType()); 2330 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg()) 2331 return false; 2332 2333 // If both the callee and the cast type are varargs, we still have to make 2334 // sure the number of fixed parameters are the same or we have the same 2335 // ABI issues as if we introduce a varargs call. 2336 if (FT->isVarArg() && 2337 cast<FunctionType>(APTy->getElementType())->isVarArg() && 2338 FT->getNumParams() != 2339 cast<FunctionType>(APTy->getElementType())->getNumParams()) 2340 return false; 2341 } 2342 2343 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && 2344 !CallerPAL.isEmpty()) 2345 // In this case we have more arguments than the new function type, but we 2346 // won't be dropping them. Check that these extra arguments have attributes 2347 // that are compatible with being a vararg call argument. 2348 for (unsigned i = CallerPAL.getNumSlots(); i; --i) { 2349 unsigned Index = CallerPAL.getSlotIndex(i - 1); 2350 if (Index <= FT->getNumParams()) 2351 break; 2352 2353 // Check if it has an attribute that's incompatible with varargs. 2354 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1); 2355 if (PAttrs.hasAttribute(Index, Attribute::StructRet)) 2356 return false; 2357 } 2358 2359 2360 // Okay, we decided that this is a safe thing to do: go ahead and start 2361 // inserting cast instructions as necessary. 2362 std::vector<Value*> Args; 2363 Args.reserve(NumActualArgs); 2364 SmallVector<AttributeSet, 8> attrVec; 2365 attrVec.reserve(NumCommonArgs); 2366 2367 // Get any return attributes. 2368 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex); 2369 2370 // If the return value is not being used, the type may not be compatible 2371 // with the existing attributes. Wipe out any problematic attributes. 2372 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy)); 2373 2374 // Add the new return attributes. 2375 if (RAttrs.hasAttributes()) 2376 attrVec.push_back(AttributeSet::get(Caller->getContext(), 2377 AttributeSet::ReturnIndex, RAttrs)); 2378 2379 AI = CS.arg_begin(); 2380 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) { 2381 Type *ParamTy = FT->getParamType(i); 2382 2383 if ((*AI)->getType() == ParamTy) { 2384 Args.push_back(*AI); 2385 } else { 2386 Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy)); 2387 } 2388 2389 // Add any parameter attributes. 2390 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1); 2391 if (PAttrs.hasAttributes()) 2392 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1, 2393 PAttrs)); 2394 } 2395 2396 // If the function takes more arguments than the call was taking, add them 2397 // now. 2398 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) 2399 Args.push_back(Constant::getNullValue(FT->getParamType(i))); 2400 2401 // If we are removing arguments to the function, emit an obnoxious warning. 2402 if (FT->getNumParams() < NumActualArgs) { 2403 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722 2404 if (FT->isVarArg()) { 2405 // Add all of the arguments in their promoted form to the arg list. 2406 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) { 2407 Type *PTy = getPromotedType((*AI)->getType()); 2408 if (PTy != (*AI)->getType()) { 2409 // Must promote to pass through va_arg area! 2410 Instruction::CastOps opcode = 2411 CastInst::getCastOpcode(*AI, false, PTy, false); 2412 Args.push_back(Builder->CreateCast(opcode, *AI, PTy)); 2413 } else { 2414 Args.push_back(*AI); 2415 } 2416 2417 // Add any parameter attributes. 2418 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1); 2419 if (PAttrs.hasAttributes()) 2420 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1, 2421 PAttrs)); 2422 } 2423 } 2424 } 2425 2426 AttributeSet FnAttrs = CallerPAL.getFnAttributes(); 2427 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex)) 2428 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs)); 2429 2430 if (NewRetTy->isVoidTy()) 2431 Caller->setName(""); // Void type should not have a name. 2432 2433 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(), 2434 attrVec); 2435 2436 SmallVector<OperandBundleDef, 1> OpBundles; 2437 CS.getOperandBundlesAsDefs(OpBundles); 2438 2439 Instruction *NC; 2440 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 2441 NC = Builder->CreateInvoke(Callee, II->getNormalDest(), II->getUnwindDest(), 2442 Args, OpBundles); 2443 NC->takeName(II); 2444 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv()); 2445 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL); 2446 } else { 2447 CallInst *CI = cast<CallInst>(Caller); 2448 NC = Builder->CreateCall(Callee, Args, OpBundles); 2449 NC->takeName(CI); 2450 if (CI->isTailCall()) 2451 cast<CallInst>(NC)->setTailCall(); 2452 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv()); 2453 cast<CallInst>(NC)->setAttributes(NewCallerPAL); 2454 } 2455 2456 // Insert a cast of the return type as necessary. 2457 Value *NV = NC; 2458 if (OldRetTy != NV->getType() && !Caller->use_empty()) { 2459 if (!NV->getType()->isVoidTy()) { 2460 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy); 2461 NC->setDebugLoc(Caller->getDebugLoc()); 2462 2463 // If this is an invoke instruction, we should insert it after the first 2464 // non-phi, instruction in the normal successor block. 2465 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 2466 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt(); 2467 InsertNewInstBefore(NC, *I); 2468 } else { 2469 // Otherwise, it's a call, just insert cast right after the call. 2470 InsertNewInstBefore(NC, *Caller); 2471 } 2472 Worklist.AddUsersToWorkList(*Caller); 2473 } else { 2474 NV = UndefValue::get(Caller->getType()); 2475 } 2476 } 2477 2478 if (!Caller->use_empty()) 2479 replaceInstUsesWith(*Caller, NV); 2480 else if (Caller->hasValueHandle()) { 2481 if (OldRetTy == NV->getType()) 2482 ValueHandleBase::ValueIsRAUWd(Caller, NV); 2483 else 2484 // We cannot call ValueIsRAUWd with a different type, and the 2485 // actual tracked value will disappear. 2486 ValueHandleBase::ValueIsDeleted(Caller); 2487 } 2488 2489 eraseInstFromFunction(*Caller); 2490 return true; 2491 } 2492 2493 /// Turn a call to a function created by init_trampoline / adjust_trampoline 2494 /// intrinsic pair into a direct call to the underlying function. 2495 Instruction * 2496 InstCombiner::transformCallThroughTrampoline(CallSite CS, 2497 IntrinsicInst *Tramp) { 2498 Value *Callee = CS.getCalledValue(); 2499 PointerType *PTy = cast<PointerType>(Callee->getType()); 2500 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 2501 const AttributeSet &Attrs = CS.getAttributes(); 2502 2503 // If the call already has the 'nest' attribute somewhere then give up - 2504 // otherwise 'nest' would occur twice after splicing in the chain. 2505 if (Attrs.hasAttrSomewhere(Attribute::Nest)) 2506 return nullptr; 2507 2508 assert(Tramp && 2509 "transformCallThroughTrampoline called with incorrect CallSite."); 2510 2511 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts()); 2512 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType()); 2513 2514 const AttributeSet &NestAttrs = NestF->getAttributes(); 2515 if (!NestAttrs.isEmpty()) { 2516 unsigned NestIdx = 1; 2517 Type *NestTy = nullptr; 2518 AttributeSet NestAttr; 2519 2520 // Look for a parameter marked with the 'nest' attribute. 2521 for (FunctionType::param_iterator I = NestFTy->param_begin(), 2522 E = NestFTy->param_end(); I != E; ++NestIdx, ++I) 2523 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) { 2524 // Record the parameter type and any other attributes. 2525 NestTy = *I; 2526 NestAttr = NestAttrs.getParamAttributes(NestIdx); 2527 break; 2528 } 2529 2530 if (NestTy) { 2531 Instruction *Caller = CS.getInstruction(); 2532 std::vector<Value*> NewArgs; 2533 NewArgs.reserve(CS.arg_size() + 1); 2534 2535 SmallVector<AttributeSet, 8> NewAttrs; 2536 NewAttrs.reserve(Attrs.getNumSlots() + 1); 2537 2538 // Insert the nest argument into the call argument list, which may 2539 // mean appending it. Likewise for attributes. 2540 2541 // Add any result attributes. 2542 if (Attrs.hasAttributes(AttributeSet::ReturnIndex)) 2543 NewAttrs.push_back(AttributeSet::get(Caller->getContext(), 2544 Attrs.getRetAttributes())); 2545 2546 { 2547 unsigned Idx = 1; 2548 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); 2549 do { 2550 if (Idx == NestIdx) { 2551 // Add the chain argument and attributes. 2552 Value *NestVal = Tramp->getArgOperand(2); 2553 if (NestVal->getType() != NestTy) 2554 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest"); 2555 NewArgs.push_back(NestVal); 2556 NewAttrs.push_back(AttributeSet::get(Caller->getContext(), 2557 NestAttr)); 2558 } 2559 2560 if (I == E) 2561 break; 2562 2563 // Add the original argument and attributes. 2564 NewArgs.push_back(*I); 2565 AttributeSet Attr = Attrs.getParamAttributes(Idx); 2566 if (Attr.hasAttributes(Idx)) { 2567 AttrBuilder B(Attr, Idx); 2568 NewAttrs.push_back(AttributeSet::get(Caller->getContext(), 2569 Idx + (Idx >= NestIdx), B)); 2570 } 2571 2572 ++Idx; 2573 ++I; 2574 } while (1); 2575 } 2576 2577 // Add any function attributes. 2578 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) 2579 NewAttrs.push_back(AttributeSet::get(FTy->getContext(), 2580 Attrs.getFnAttributes())); 2581 2582 // The trampoline may have been bitcast to a bogus type (FTy). 2583 // Handle this by synthesizing a new function type, equal to FTy 2584 // with the chain parameter inserted. 2585 2586 std::vector<Type*> NewTypes; 2587 NewTypes.reserve(FTy->getNumParams()+1); 2588 2589 // Insert the chain's type into the list of parameter types, which may 2590 // mean appending it. 2591 { 2592 unsigned Idx = 1; 2593 FunctionType::param_iterator I = FTy->param_begin(), 2594 E = FTy->param_end(); 2595 2596 do { 2597 if (Idx == NestIdx) 2598 // Add the chain's type. 2599 NewTypes.push_back(NestTy); 2600 2601 if (I == E) 2602 break; 2603 2604 // Add the original type. 2605 NewTypes.push_back(*I); 2606 2607 ++Idx; 2608 ++I; 2609 } while (1); 2610 } 2611 2612 // Replace the trampoline call with a direct call. Let the generic 2613 // code sort out any function type mismatches. 2614 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 2615 FTy->isVarArg()); 2616 Constant *NewCallee = 2617 NestF->getType() == PointerType::getUnqual(NewFTy) ? 2618 NestF : ConstantExpr::getBitCast(NestF, 2619 PointerType::getUnqual(NewFTy)); 2620 const AttributeSet &NewPAL = 2621 AttributeSet::get(FTy->getContext(), NewAttrs); 2622 2623 Instruction *NewCaller; 2624 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 2625 NewCaller = InvokeInst::Create(NewCallee, 2626 II->getNormalDest(), II->getUnwindDest(), 2627 NewArgs); 2628 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv()); 2629 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL); 2630 } else { 2631 NewCaller = CallInst::Create(NewCallee, NewArgs); 2632 if (cast<CallInst>(Caller)->isTailCall()) 2633 cast<CallInst>(NewCaller)->setTailCall(); 2634 cast<CallInst>(NewCaller)-> 2635 setCallingConv(cast<CallInst>(Caller)->getCallingConv()); 2636 cast<CallInst>(NewCaller)->setAttributes(NewPAL); 2637 } 2638 2639 return NewCaller; 2640 } 2641 } 2642 2643 // Replace the trampoline call with a direct call. Since there is no 'nest' 2644 // parameter, there is no need to adjust the argument list. Let the generic 2645 // code sort out any function type mismatches. 2646 Constant *NewCallee = 2647 NestF->getType() == PTy ? NestF : 2648 ConstantExpr::getBitCast(NestF, PTy); 2649 CS.setCalledFunction(NewCallee); 2650 return CS.getInstruction(); 2651 } 2652