1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // InstructionCombining - Combine instructions to form fewer, simple 10 // instructions. This pass does not modify the CFG. This pass is where 11 // algebraic simplification happens. 12 // 13 // This pass combines things like: 14 // %Y = add i32 %X, 1 15 // %Z = add i32 %Y, 1 16 // into: 17 // %Z = add i32 %X, 2 18 // 19 // This is a simple worklist driven algorithm. 20 // 21 // This pass guarantees that the following canonicalizations are performed on 22 // the program: 23 // 1. If a binary operator has a constant operand, it is moved to the RHS 24 // 2. Bitwise operators with constant operands are always grouped so that 25 // shifts are performed first, then or's, then and's, then xor's. 26 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible 27 // 4. All cmp instructions on boolean values are replaced with logical ops 28 // 5. add X, X is represented as (X*2) => (X << 1) 29 // 6. Multiplies with a power-of-two constant argument are transformed into 30 // shifts. 31 // ... etc. 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "InstCombineInternal.h" 36 #include "llvm-c/Initialization.h" 37 #include "llvm-c/Transforms/InstCombine.h" 38 #include "llvm/ADT/APInt.h" 39 #include "llvm/ADT/ArrayRef.h" 40 #include "llvm/ADT/DenseMap.h" 41 #include "llvm/ADT/None.h" 42 #include "llvm/ADT/SmallPtrSet.h" 43 #include "llvm/ADT/SmallVector.h" 44 #include "llvm/ADT/Statistic.h" 45 #include "llvm/ADT/TinyPtrVector.h" 46 #include "llvm/Analysis/AliasAnalysis.h" 47 #include "llvm/Analysis/AssumptionCache.h" 48 #include "llvm/Analysis/BasicAliasAnalysis.h" 49 #include "llvm/Analysis/CFG.h" 50 #include "llvm/Analysis/ConstantFolding.h" 51 #include "llvm/Analysis/EHPersonalities.h" 52 #include "llvm/Analysis/GlobalsModRef.h" 53 #include "llvm/Analysis/InstructionSimplify.h" 54 #include "llvm/Analysis/LoopInfo.h" 55 #include "llvm/Analysis/MemoryBuiltins.h" 56 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 57 #include "llvm/Analysis/TargetFolder.h" 58 #include "llvm/Analysis/TargetLibraryInfo.h" 59 #include "llvm/Analysis/ValueTracking.h" 60 #include "llvm/IR/BasicBlock.h" 61 #include "llvm/IR/CFG.h" 62 #include "llvm/IR/Constant.h" 63 #include "llvm/IR/Constants.h" 64 #include "llvm/IR/DIBuilder.h" 65 #include "llvm/IR/DataLayout.h" 66 #include "llvm/IR/DerivedTypes.h" 67 #include "llvm/IR/Dominators.h" 68 #include "llvm/IR/Function.h" 69 #include "llvm/IR/GetElementPtrTypeIterator.h" 70 #include "llvm/IR/IRBuilder.h" 71 #include "llvm/IR/InstrTypes.h" 72 #include "llvm/IR/Instruction.h" 73 #include "llvm/IR/Instructions.h" 74 #include "llvm/IR/IntrinsicInst.h" 75 #include "llvm/IR/Intrinsics.h" 76 #include "llvm/IR/LegacyPassManager.h" 77 #include "llvm/IR/Metadata.h" 78 #include "llvm/IR/Operator.h" 79 #include "llvm/IR/PassManager.h" 80 #include "llvm/IR/PatternMatch.h" 81 #include "llvm/IR/Type.h" 82 #include "llvm/IR/Use.h" 83 #include "llvm/IR/User.h" 84 #include "llvm/IR/Value.h" 85 #include "llvm/IR/ValueHandle.h" 86 #include "llvm/Pass.h" 87 #include "llvm/Support/CBindingWrapping.h" 88 #include "llvm/Support/Casting.h" 89 #include "llvm/Support/CommandLine.h" 90 #include "llvm/Support/Compiler.h" 91 #include "llvm/Support/Debug.h" 92 #include "llvm/Support/DebugCounter.h" 93 #include "llvm/Support/ErrorHandling.h" 94 #include "llvm/Support/KnownBits.h" 95 #include "llvm/Support/raw_ostream.h" 96 #include "llvm/Transforms/InstCombine/InstCombine.h" 97 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" 98 #include "llvm/Transforms/Utils/Local.h" 99 #include <algorithm> 100 #include <cassert> 101 #include <cstdint> 102 #include <memory> 103 #include <string> 104 #include <utility> 105 106 using namespace llvm; 107 using namespace llvm::PatternMatch; 108 109 #define DEBUG_TYPE "instcombine" 110 111 STATISTIC(NumCombined , "Number of insts combined"); 112 STATISTIC(NumConstProp, "Number of constant folds"); 113 STATISTIC(NumDeadInst , "Number of dead inst eliminated"); 114 STATISTIC(NumSunkInst , "Number of instructions sunk"); 115 STATISTIC(NumExpand, "Number of expansions"); 116 STATISTIC(NumFactor , "Number of factorizations"); 117 STATISTIC(NumReassoc , "Number of reassociations"); 118 DEBUG_COUNTER(VisitCounter, "instcombine-visit", 119 "Controls which instructions are visited"); 120 121 static cl::opt<bool> 122 EnableCodeSinking("instcombine-code-sinking", cl::desc("Enable code sinking"), 123 cl::init(true)); 124 125 static cl::opt<bool> 126 EnableExpensiveCombines("expensive-combines", 127 cl::desc("Enable expensive instruction combines")); 128 129 static cl::opt<unsigned> 130 MaxArraySize("instcombine-maxarray-size", cl::init(1024), 131 cl::desc("Maximum array size considered when doing a combine")); 132 133 // FIXME: Remove this flag when it is no longer necessary to convert 134 // llvm.dbg.declare to avoid inaccurate debug info. Setting this to false 135 // increases variable availability at the cost of accuracy. Variables that 136 // cannot be promoted by mem2reg or SROA will be described as living in memory 137 // for their entire lifetime. However, passes like DSE and instcombine can 138 // delete stores to the alloca, leading to misleading and inaccurate debug 139 // information. This flag can be removed when those passes are fixed. 140 static cl::opt<unsigned> ShouldLowerDbgDeclare("instcombine-lower-dbg-declare", 141 cl::Hidden, cl::init(true)); 142 143 Value *InstCombiner::EmitGEPOffset(User *GEP) { 144 return llvm::EmitGEPOffset(&Builder, DL, GEP); 145 } 146 147 /// Return true if it is desirable to convert an integer computation from a 148 /// given bit width to a new bit width. 149 /// We don't want to convert from a legal to an illegal type or from a smaller 150 /// to a larger illegal type. A width of '1' is always treated as a legal type 151 /// because i1 is a fundamental type in IR, and there are many specialized 152 /// optimizations for i1 types. Widths of 8, 16 or 32 are equally treated as 153 /// legal to convert to, in order to open up more combining opportunities. 154 /// NOTE: this treats i8, i16 and i32 specially, due to them being so common 155 /// from frontend languages. 156 bool InstCombiner::shouldChangeType(unsigned FromWidth, 157 unsigned ToWidth) const { 158 bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth); 159 bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth); 160 161 // Convert to widths of 8, 16 or 32 even if they are not legal types. Only 162 // shrink types, to prevent infinite loops. 163 if (ToWidth < FromWidth && (ToWidth == 8 || ToWidth == 16 || ToWidth == 32)) 164 return true; 165 166 // If this is a legal integer from type, and the result would be an illegal 167 // type, don't do the transformation. 168 if (FromLegal && !ToLegal) 169 return false; 170 171 // Otherwise, if both are illegal, do not increase the size of the result. We 172 // do allow things like i160 -> i64, but not i64 -> i160. 173 if (!FromLegal && !ToLegal && ToWidth > FromWidth) 174 return false; 175 176 return true; 177 } 178 179 /// Return true if it is desirable to convert a computation from 'From' to 'To'. 180 /// We don't want to convert from a legal to an illegal type or from a smaller 181 /// to a larger illegal type. i1 is always treated as a legal type because it is 182 /// a fundamental type in IR, and there are many specialized optimizations for 183 /// i1 types. 184 bool InstCombiner::shouldChangeType(Type *From, Type *To) const { 185 // TODO: This could be extended to allow vectors. Datalayout changes might be 186 // needed to properly support that. 187 if (!From->isIntegerTy() || !To->isIntegerTy()) 188 return false; 189 190 unsigned FromWidth = From->getPrimitiveSizeInBits(); 191 unsigned ToWidth = To->getPrimitiveSizeInBits(); 192 return shouldChangeType(FromWidth, ToWidth); 193 } 194 195 // Return true, if No Signed Wrap should be maintained for I. 196 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C", 197 // where both B and C should be ConstantInts, results in a constant that does 198 // not overflow. This function only handles the Add and Sub opcodes. For 199 // all other opcodes, the function conservatively returns false. 200 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) { 201 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I); 202 if (!OBO || !OBO->hasNoSignedWrap()) 203 return false; 204 205 // We reason about Add and Sub Only. 206 Instruction::BinaryOps Opcode = I.getOpcode(); 207 if (Opcode != Instruction::Add && Opcode != Instruction::Sub) 208 return false; 209 210 const APInt *BVal, *CVal; 211 if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal))) 212 return false; 213 214 bool Overflow = false; 215 if (Opcode == Instruction::Add) 216 (void)BVal->sadd_ov(*CVal, Overflow); 217 else 218 (void)BVal->ssub_ov(*CVal, Overflow); 219 220 return !Overflow; 221 } 222 223 /// Conservatively clears subclassOptionalData after a reassociation or 224 /// commutation. We preserve fast-math flags when applicable as they can be 225 /// preserved. 226 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) { 227 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I); 228 if (!FPMO) { 229 I.clearSubclassOptionalData(); 230 return; 231 } 232 233 FastMathFlags FMF = I.getFastMathFlags(); 234 I.clearSubclassOptionalData(); 235 I.setFastMathFlags(FMF); 236 } 237 238 /// Combine constant operands of associative operations either before or after a 239 /// cast to eliminate one of the associative operations: 240 /// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2))) 241 /// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2)) 242 static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1) { 243 auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0)); 244 if (!Cast || !Cast->hasOneUse()) 245 return false; 246 247 // TODO: Enhance logic for other casts and remove this check. 248 auto CastOpcode = Cast->getOpcode(); 249 if (CastOpcode != Instruction::ZExt) 250 return false; 251 252 // TODO: Enhance logic for other BinOps and remove this check. 253 if (!BinOp1->isBitwiseLogicOp()) 254 return false; 255 256 auto AssocOpcode = BinOp1->getOpcode(); 257 auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0)); 258 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode) 259 return false; 260 261 Constant *C1, *C2; 262 if (!match(BinOp1->getOperand(1), m_Constant(C1)) || 263 !match(BinOp2->getOperand(1), m_Constant(C2))) 264 return false; 265 266 // TODO: This assumes a zext cast. 267 // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2 268 // to the destination type might lose bits. 269 270 // Fold the constants together in the destination type: 271 // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC) 272 Type *DestTy = C1->getType(); 273 Constant *CastC2 = ConstantExpr::getCast(CastOpcode, C2, DestTy); 274 Constant *FoldedC = ConstantExpr::get(AssocOpcode, C1, CastC2); 275 Cast->setOperand(0, BinOp2->getOperand(0)); 276 BinOp1->setOperand(1, FoldedC); 277 return true; 278 } 279 280 /// This performs a few simplifications for operators that are associative or 281 /// commutative: 282 /// 283 /// Commutative operators: 284 /// 285 /// 1. Order operands such that they are listed from right (least complex) to 286 /// left (most complex). This puts constants before unary operators before 287 /// binary operators. 288 /// 289 /// Associative operators: 290 /// 291 /// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. 292 /// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. 293 /// 294 /// Associative and commutative operators: 295 /// 296 /// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. 297 /// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. 298 /// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" 299 /// if C1 and C2 are constants. 300 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) { 301 Instruction::BinaryOps Opcode = I.getOpcode(); 302 bool Changed = false; 303 304 do { 305 // Order operands such that they are listed from right (least complex) to 306 // left (most complex). This puts constants before unary operators before 307 // binary operators. 308 if (I.isCommutative() && getComplexity(I.getOperand(0)) < 309 getComplexity(I.getOperand(1))) 310 Changed = !I.swapOperands(); 311 312 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0)); 313 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)); 314 315 if (I.isAssociative()) { 316 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. 317 if (Op0 && Op0->getOpcode() == Opcode) { 318 Value *A = Op0->getOperand(0); 319 Value *B = Op0->getOperand(1); 320 Value *C = I.getOperand(1); 321 322 // Does "B op C" simplify? 323 if (Value *V = SimplifyBinOp(Opcode, B, C, SQ.getWithInstruction(&I))) { 324 // It simplifies to V. Form "A op V". 325 I.setOperand(0, A); 326 I.setOperand(1, V); 327 // Conservatively clear the optional flags, since they may not be 328 // preserved by the reassociation. 329 if (MaintainNoSignedWrap(I, B, C) && 330 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) { 331 // Note: this is only valid because SimplifyBinOp doesn't look at 332 // the operands to Op0. 333 I.clearSubclassOptionalData(); 334 I.setHasNoSignedWrap(true); 335 } else { 336 ClearSubclassDataAfterReassociation(I); 337 } 338 339 Changed = true; 340 ++NumReassoc; 341 continue; 342 } 343 } 344 345 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. 346 if (Op1 && Op1->getOpcode() == Opcode) { 347 Value *A = I.getOperand(0); 348 Value *B = Op1->getOperand(0); 349 Value *C = Op1->getOperand(1); 350 351 // Does "A op B" simplify? 352 if (Value *V = SimplifyBinOp(Opcode, A, B, SQ.getWithInstruction(&I))) { 353 // It simplifies to V. Form "V op C". 354 I.setOperand(0, V); 355 I.setOperand(1, C); 356 // Conservatively clear the optional flags, since they may not be 357 // preserved by the reassociation. 358 ClearSubclassDataAfterReassociation(I); 359 Changed = true; 360 ++NumReassoc; 361 continue; 362 } 363 } 364 } 365 366 if (I.isAssociative() && I.isCommutative()) { 367 if (simplifyAssocCastAssoc(&I)) { 368 Changed = true; 369 ++NumReassoc; 370 continue; 371 } 372 373 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. 374 if (Op0 && Op0->getOpcode() == Opcode) { 375 Value *A = Op0->getOperand(0); 376 Value *B = Op0->getOperand(1); 377 Value *C = I.getOperand(1); 378 379 // Does "C op A" simplify? 380 if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) { 381 // It simplifies to V. Form "V op B". 382 I.setOperand(0, V); 383 I.setOperand(1, B); 384 // Conservatively clear the optional flags, since they may not be 385 // preserved by the reassociation. 386 ClearSubclassDataAfterReassociation(I); 387 Changed = true; 388 ++NumReassoc; 389 continue; 390 } 391 } 392 393 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. 394 if (Op1 && Op1->getOpcode() == Opcode) { 395 Value *A = I.getOperand(0); 396 Value *B = Op1->getOperand(0); 397 Value *C = Op1->getOperand(1); 398 399 // Does "C op A" simplify? 400 if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) { 401 // It simplifies to V. Form "B op V". 402 I.setOperand(0, B); 403 I.setOperand(1, V); 404 // Conservatively clear the optional flags, since they may not be 405 // preserved by the reassociation. 406 ClearSubclassDataAfterReassociation(I); 407 Changed = true; 408 ++NumReassoc; 409 continue; 410 } 411 } 412 413 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" 414 // if C1 and C2 are constants. 415 Value *A, *B; 416 Constant *C1, *C2; 417 if (Op0 && Op1 && 418 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode && 419 match(Op0, m_OneUse(m_BinOp(m_Value(A), m_Constant(C1)))) && 420 match(Op1, m_OneUse(m_BinOp(m_Value(B), m_Constant(C2))))) { 421 BinaryOperator *NewBO = BinaryOperator::Create(Opcode, A, B); 422 if (isa<FPMathOperator>(NewBO)) { 423 FastMathFlags Flags = I.getFastMathFlags(); 424 Flags &= Op0->getFastMathFlags(); 425 Flags &= Op1->getFastMathFlags(); 426 NewBO->setFastMathFlags(Flags); 427 } 428 InsertNewInstWith(NewBO, I); 429 NewBO->takeName(Op1); 430 I.setOperand(0, NewBO); 431 I.setOperand(1, ConstantExpr::get(Opcode, C1, C2)); 432 // Conservatively clear the optional flags, since they may not be 433 // preserved by the reassociation. 434 ClearSubclassDataAfterReassociation(I); 435 436 Changed = true; 437 continue; 438 } 439 } 440 441 // No further simplifications. 442 return Changed; 443 } while (true); 444 } 445 446 /// Return whether "X LOp (Y ROp Z)" is always equal to 447 /// "(X LOp Y) ROp (X LOp Z)". 448 static bool leftDistributesOverRight(Instruction::BinaryOps LOp, 449 Instruction::BinaryOps ROp) { 450 // X & (Y | Z) <--> (X & Y) | (X & Z) 451 // X & (Y ^ Z) <--> (X & Y) ^ (X & Z) 452 if (LOp == Instruction::And) 453 return ROp == Instruction::Or || ROp == Instruction::Xor; 454 455 // X | (Y & Z) <--> (X | Y) & (X | Z) 456 if (LOp == Instruction::Or) 457 return ROp == Instruction::And; 458 459 // X * (Y + Z) <--> (X * Y) + (X * Z) 460 // X * (Y - Z) <--> (X * Y) - (X * Z) 461 if (LOp == Instruction::Mul) 462 return ROp == Instruction::Add || ROp == Instruction::Sub; 463 464 return false; 465 } 466 467 /// Return whether "(X LOp Y) ROp Z" is always equal to 468 /// "(X ROp Z) LOp (Y ROp Z)". 469 static bool rightDistributesOverLeft(Instruction::BinaryOps LOp, 470 Instruction::BinaryOps ROp) { 471 if (Instruction::isCommutative(ROp)) 472 return leftDistributesOverRight(ROp, LOp); 473 474 // (X {&|^} Y) >> Z <--> (X >> Z) {&|^} (Y >> Z) for all shifts. 475 return Instruction::isBitwiseLogicOp(LOp) && Instruction::isShift(ROp); 476 477 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z", 478 // but this requires knowing that the addition does not overflow and other 479 // such subtleties. 480 } 481 482 /// This function returns identity value for given opcode, which can be used to 483 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1). 484 static Value *getIdentityValue(Instruction::BinaryOps Opcode, Value *V) { 485 if (isa<Constant>(V)) 486 return nullptr; 487 488 return ConstantExpr::getBinOpIdentity(Opcode, V->getType()); 489 } 490 491 /// This function predicates factorization using distributive laws. By default, 492 /// it just returns the 'Op' inputs. But for special-cases like 493 /// 'add(shl(X, 5), ...)', this function will have TopOpcode == Instruction::Add 494 /// and Op = shl(X, 5). The 'shl' is treated as the more general 'mul X, 32' to 495 /// allow more factorization opportunities. 496 static Instruction::BinaryOps 497 getBinOpsForFactorization(Instruction::BinaryOps TopOpcode, BinaryOperator *Op, 498 Value *&LHS, Value *&RHS) { 499 assert(Op && "Expected a binary operator"); 500 LHS = Op->getOperand(0); 501 RHS = Op->getOperand(1); 502 if (TopOpcode == Instruction::Add || TopOpcode == Instruction::Sub) { 503 Constant *C; 504 if (match(Op, m_Shl(m_Value(), m_Constant(C)))) { 505 // X << C --> X * (1 << C) 506 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), C); 507 return Instruction::Mul; 508 } 509 // TODO: We can add other conversions e.g. shr => div etc. 510 } 511 return Op->getOpcode(); 512 } 513 514 /// This tries to simplify binary operations by factorizing out common terms 515 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)"). 516 Value *InstCombiner::tryFactorization(BinaryOperator &I, 517 Instruction::BinaryOps InnerOpcode, 518 Value *A, Value *B, Value *C, Value *D) { 519 assert(A && B && C && D && "All values must be provided"); 520 521 Value *V = nullptr; 522 Value *SimplifiedInst = nullptr; 523 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 524 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); 525 526 // Does "X op' Y" always equal "Y op' X"? 527 bool InnerCommutative = Instruction::isCommutative(InnerOpcode); 528 529 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"? 530 if (leftDistributesOverRight(InnerOpcode, TopLevelOpcode)) 531 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the 532 // commutative case, "(A op' B) op (C op' A)"? 533 if (A == C || (InnerCommutative && A == D)) { 534 if (A != C) 535 std::swap(C, D); 536 // Consider forming "A op' (B op D)". 537 // If "B op D" simplifies then it can be formed with no cost. 538 V = SimplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I)); 539 // If "B op D" doesn't simplify then only go on if both of the existing 540 // operations "A op' B" and "C op' D" will be zapped as no longer used. 541 if (!V && LHS->hasOneUse() && RHS->hasOneUse()) 542 V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->getName()); 543 if (V) { 544 SimplifiedInst = Builder.CreateBinOp(InnerOpcode, A, V); 545 } 546 } 547 548 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"? 549 if (!SimplifiedInst && rightDistributesOverLeft(TopLevelOpcode, InnerOpcode)) 550 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the 551 // commutative case, "(A op' B) op (B op' D)"? 552 if (B == D || (InnerCommutative && B == C)) { 553 if (B != D) 554 std::swap(C, D); 555 // Consider forming "(A op C) op' B". 556 // If "A op C" simplifies then it can be formed with no cost. 557 V = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I)); 558 559 // If "A op C" doesn't simplify then only go on if both of the existing 560 // operations "A op' B" and "C op' D" will be zapped as no longer used. 561 if (!V && LHS->hasOneUse() && RHS->hasOneUse()) 562 V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->getName()); 563 if (V) { 564 SimplifiedInst = Builder.CreateBinOp(InnerOpcode, V, B); 565 } 566 } 567 568 if (SimplifiedInst) { 569 ++NumFactor; 570 SimplifiedInst->takeName(&I); 571 572 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag. 573 // TODO: Check for NUW. 574 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) { 575 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) { 576 bool HasNSW = false; 577 if (isa<OverflowingBinaryOperator>(&I)) 578 HasNSW = I.hasNoSignedWrap(); 579 580 if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS)) 581 HasNSW &= LOBO->hasNoSignedWrap(); 582 583 if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS)) 584 HasNSW &= ROBO->hasNoSignedWrap(); 585 586 // We can propagate 'nsw' if we know that 587 // %Y = mul nsw i16 %X, C 588 // %Z = add nsw i16 %Y, %X 589 // => 590 // %Z = mul nsw i16 %X, C+1 591 // 592 // iff C+1 isn't INT_MIN 593 const APInt *CInt; 594 if (TopLevelOpcode == Instruction::Add && 595 InnerOpcode == Instruction::Mul) 596 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue()) 597 BO->setHasNoSignedWrap(HasNSW); 598 } 599 } 600 } 601 return SimplifiedInst; 602 } 603 604 /// This tries to simplify binary operations which some other binary operation 605 /// distributes over either by factorizing out common terms 606 /// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in 607 /// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win). 608 /// Returns the simplified value, or null if it didn't simplify. 609 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) { 610 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 611 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); 612 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); 613 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); 614 615 { 616 // Factorization. 617 Value *A, *B, *C, *D; 618 Instruction::BinaryOps LHSOpcode, RHSOpcode; 619 if (Op0) 620 LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B); 621 if (Op1) 622 RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D); 623 624 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize 625 // a common term. 626 if (Op0 && Op1 && LHSOpcode == RHSOpcode) 627 if (Value *V = tryFactorization(I, LHSOpcode, A, B, C, D)) 628 return V; 629 630 // The instruction has the form "(A op' B) op (C)". Try to factorize common 631 // term. 632 if (Op0) 633 if (Value *Ident = getIdentityValue(LHSOpcode, RHS)) 634 if (Value *V = tryFactorization(I, LHSOpcode, A, B, RHS, Ident)) 635 return V; 636 637 // The instruction has the form "(B) op (C op' D)". Try to factorize common 638 // term. 639 if (Op1) 640 if (Value *Ident = getIdentityValue(RHSOpcode, LHS)) 641 if (Value *V = tryFactorization(I, RHSOpcode, LHS, Ident, C, D)) 642 return V; 643 } 644 645 // Expansion. 646 if (Op0 && rightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) { 647 // The instruction has the form "(A op' B) op C". See if expanding it out 648 // to "(A op C) op' (B op C)" results in simplifications. 649 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS; 650 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op' 651 652 Value *L = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I)); 653 Value *R = SimplifyBinOp(TopLevelOpcode, B, C, SQ.getWithInstruction(&I)); 654 655 // Do "A op C" and "B op C" both simplify? 656 if (L && R) { 657 // They do! Return "L op' R". 658 ++NumExpand; 659 C = Builder.CreateBinOp(InnerOpcode, L, R); 660 C->takeName(&I); 661 return C; 662 } 663 664 // Does "A op C" simplify to the identity value for the inner opcode? 665 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) { 666 // They do! Return "B op C". 667 ++NumExpand; 668 C = Builder.CreateBinOp(TopLevelOpcode, B, C); 669 C->takeName(&I); 670 return C; 671 } 672 673 // Does "B op C" simplify to the identity value for the inner opcode? 674 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) { 675 // They do! Return "A op C". 676 ++NumExpand; 677 C = Builder.CreateBinOp(TopLevelOpcode, A, C); 678 C->takeName(&I); 679 return C; 680 } 681 } 682 683 if (Op1 && leftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) { 684 // The instruction has the form "A op (B op' C)". See if expanding it out 685 // to "(A op B) op' (A op C)" results in simplifications. 686 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1); 687 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op' 688 689 Value *L = SimplifyBinOp(TopLevelOpcode, A, B, SQ.getWithInstruction(&I)); 690 Value *R = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I)); 691 692 // Do "A op B" and "A op C" both simplify? 693 if (L && R) { 694 // They do! Return "L op' R". 695 ++NumExpand; 696 A = Builder.CreateBinOp(InnerOpcode, L, R); 697 A->takeName(&I); 698 return A; 699 } 700 701 // Does "A op B" simplify to the identity value for the inner opcode? 702 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) { 703 // They do! Return "A op C". 704 ++NumExpand; 705 A = Builder.CreateBinOp(TopLevelOpcode, A, C); 706 A->takeName(&I); 707 return A; 708 } 709 710 // Does "A op C" simplify to the identity value for the inner opcode? 711 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) { 712 // They do! Return "A op B". 713 ++NumExpand; 714 A = Builder.CreateBinOp(TopLevelOpcode, A, B); 715 A->takeName(&I); 716 return A; 717 } 718 } 719 720 return SimplifySelectsFeedingBinaryOp(I, LHS, RHS); 721 } 722 723 Value *InstCombiner::SimplifySelectsFeedingBinaryOp(BinaryOperator &I, 724 Value *LHS, Value *RHS) { 725 Instruction::BinaryOps Opcode = I.getOpcode(); 726 // (op (select (a, b, c)), (select (a, d, e))) -> (select (a, (op b, d), (op 727 // c, e))) 728 Value *A, *B, *C, *D, *E; 729 Value *SI = nullptr; 730 if (match(LHS, m_Select(m_Value(A), m_Value(B), m_Value(C))) && 731 match(RHS, m_Select(m_Specific(A), m_Value(D), m_Value(E)))) { 732 bool SelectsHaveOneUse = LHS->hasOneUse() && RHS->hasOneUse(); 733 BuilderTy::FastMathFlagGuard Guard(Builder); 734 if (isa<FPMathOperator>(&I)) 735 Builder.setFastMathFlags(I.getFastMathFlags()); 736 737 Value *V1 = SimplifyBinOp(Opcode, C, E, SQ.getWithInstruction(&I)); 738 Value *V2 = SimplifyBinOp(Opcode, B, D, SQ.getWithInstruction(&I)); 739 if (V1 && V2) 740 SI = Builder.CreateSelect(A, V2, V1); 741 else if (V2 && SelectsHaveOneUse) 742 SI = Builder.CreateSelect(A, V2, Builder.CreateBinOp(Opcode, C, E)); 743 else if (V1 && SelectsHaveOneUse) 744 SI = Builder.CreateSelect(A, Builder.CreateBinOp(Opcode, B, D), V1); 745 746 if (SI) 747 SI->takeName(&I); 748 } 749 750 return SI; 751 } 752 753 /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a 754 /// constant zero (which is the 'negate' form). 755 Value *InstCombiner::dyn_castNegVal(Value *V) const { 756 Value *NegV; 757 if (match(V, m_Neg(m_Value(NegV)))) 758 return NegV; 759 760 // Constants can be considered to be negated values if they can be folded. 761 if (ConstantInt *C = dyn_cast<ConstantInt>(V)) 762 return ConstantExpr::getNeg(C); 763 764 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V)) 765 if (C->getType()->getElementType()->isIntegerTy()) 766 return ConstantExpr::getNeg(C); 767 768 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) { 769 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) { 770 Constant *Elt = CV->getAggregateElement(i); 771 if (!Elt) 772 return nullptr; 773 774 if (isa<UndefValue>(Elt)) 775 continue; 776 777 if (!isa<ConstantInt>(Elt)) 778 return nullptr; 779 } 780 return ConstantExpr::getNeg(CV); 781 } 782 783 return nullptr; 784 } 785 786 static Value *foldOperationIntoSelectOperand(Instruction &I, Value *SO, 787 InstCombiner::BuilderTy &Builder) { 788 if (auto *Cast = dyn_cast<CastInst>(&I)) 789 return Builder.CreateCast(Cast->getOpcode(), SO, I.getType()); 790 791 assert(I.isBinaryOp() && "Unexpected opcode for select folding"); 792 793 // Figure out if the constant is the left or the right argument. 794 bool ConstIsRHS = isa<Constant>(I.getOperand(1)); 795 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS)); 796 797 if (auto *SOC = dyn_cast<Constant>(SO)) { 798 if (ConstIsRHS) 799 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand); 800 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC); 801 } 802 803 Value *Op0 = SO, *Op1 = ConstOperand; 804 if (!ConstIsRHS) 805 std::swap(Op0, Op1); 806 807 auto *BO = cast<BinaryOperator>(&I); 808 Value *RI = Builder.CreateBinOp(BO->getOpcode(), Op0, Op1, 809 SO->getName() + ".op"); 810 auto *FPInst = dyn_cast<Instruction>(RI); 811 if (FPInst && isa<FPMathOperator>(FPInst)) 812 FPInst->copyFastMathFlags(BO); 813 return RI; 814 } 815 816 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) { 817 // Don't modify shared select instructions. 818 if (!SI->hasOneUse()) 819 return nullptr; 820 821 Value *TV = SI->getTrueValue(); 822 Value *FV = SI->getFalseValue(); 823 if (!(isa<Constant>(TV) || isa<Constant>(FV))) 824 return nullptr; 825 826 // Bool selects with constant operands can be folded to logical ops. 827 if (SI->getType()->isIntOrIntVectorTy(1)) 828 return nullptr; 829 830 // If it's a bitcast involving vectors, make sure it has the same number of 831 // elements on both sides. 832 if (auto *BC = dyn_cast<BitCastInst>(&Op)) { 833 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy()); 834 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy()); 835 836 // Verify that either both or neither are vectors. 837 if ((SrcTy == nullptr) != (DestTy == nullptr)) 838 return nullptr; 839 840 // If vectors, verify that they have the same number of elements. 841 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements()) 842 return nullptr; 843 } 844 845 // Test if a CmpInst instruction is used exclusively by a select as 846 // part of a minimum or maximum operation. If so, refrain from doing 847 // any other folding. This helps out other analyses which understand 848 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution 849 // and CodeGen. And in this case, at least one of the comparison 850 // operands has at least one user besides the compare (the select), 851 // which would often largely negate the benefit of folding anyway. 852 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) { 853 if (CI->hasOneUse()) { 854 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1); 855 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) || 856 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1)) 857 return nullptr; 858 } 859 } 860 861 Value *NewTV = foldOperationIntoSelectOperand(Op, TV, Builder); 862 Value *NewFV = foldOperationIntoSelectOperand(Op, FV, Builder); 863 return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI); 864 } 865 866 static Value *foldOperationIntoPhiValue(BinaryOperator *I, Value *InV, 867 InstCombiner::BuilderTy &Builder) { 868 bool ConstIsRHS = isa<Constant>(I->getOperand(1)); 869 Constant *C = cast<Constant>(I->getOperand(ConstIsRHS)); 870 871 if (auto *InC = dyn_cast<Constant>(InV)) { 872 if (ConstIsRHS) 873 return ConstantExpr::get(I->getOpcode(), InC, C); 874 return ConstantExpr::get(I->getOpcode(), C, InC); 875 } 876 877 Value *Op0 = InV, *Op1 = C; 878 if (!ConstIsRHS) 879 std::swap(Op0, Op1); 880 881 Value *RI = Builder.CreateBinOp(I->getOpcode(), Op0, Op1, "phitmp"); 882 auto *FPInst = dyn_cast<Instruction>(RI); 883 if (FPInst && isa<FPMathOperator>(FPInst)) 884 FPInst->copyFastMathFlags(I); 885 return RI; 886 } 887 888 Instruction *InstCombiner::foldOpIntoPhi(Instruction &I, PHINode *PN) { 889 unsigned NumPHIValues = PN->getNumIncomingValues(); 890 if (NumPHIValues == 0) 891 return nullptr; 892 893 // We normally only transform phis with a single use. However, if a PHI has 894 // multiple uses and they are all the same operation, we can fold *all* of the 895 // uses into the PHI. 896 if (!PN->hasOneUse()) { 897 // Walk the use list for the instruction, comparing them to I. 898 for (User *U : PN->users()) { 899 Instruction *UI = cast<Instruction>(U); 900 if (UI != &I && !I.isIdenticalTo(UI)) 901 return nullptr; 902 } 903 // Otherwise, we can replace *all* users with the new PHI we form. 904 } 905 906 // Check to see if all of the operands of the PHI are simple constants 907 // (constantint/constantfp/undef). If there is one non-constant value, 908 // remember the BB it is in. If there is more than one or if *it* is a PHI, 909 // bail out. We don't do arbitrary constant expressions here because moving 910 // their computation can be expensive without a cost model. 911 BasicBlock *NonConstBB = nullptr; 912 for (unsigned i = 0; i != NumPHIValues; ++i) { 913 Value *InVal = PN->getIncomingValue(i); 914 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal)) 915 continue; 916 917 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi. 918 if (NonConstBB) return nullptr; // More than one non-const value. 919 920 NonConstBB = PN->getIncomingBlock(i); 921 922 // If the InVal is an invoke at the end of the pred block, then we can't 923 // insert a computation after it without breaking the edge. 924 if (isa<InvokeInst>(InVal)) 925 if (cast<Instruction>(InVal)->getParent() == NonConstBB) 926 return nullptr; 927 928 // If the incoming non-constant value is in I's block, we will remove one 929 // instruction, but insert another equivalent one, leading to infinite 930 // instcombine. 931 if (isPotentiallyReachable(I.getParent(), NonConstBB, &DT, LI)) 932 return nullptr; 933 } 934 935 // If there is exactly one non-constant value, we can insert a copy of the 936 // operation in that block. However, if this is a critical edge, we would be 937 // inserting the computation on some other paths (e.g. inside a loop). Only 938 // do this if the pred block is unconditionally branching into the phi block. 939 if (NonConstBB != nullptr) { 940 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator()); 941 if (!BI || !BI->isUnconditional()) return nullptr; 942 } 943 944 // Okay, we can do the transformation: create the new PHI node. 945 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues()); 946 InsertNewInstBefore(NewPN, *PN); 947 NewPN->takeName(PN); 948 949 // If we are going to have to insert a new computation, do so right before the 950 // predecessor's terminator. 951 if (NonConstBB) 952 Builder.SetInsertPoint(NonConstBB->getTerminator()); 953 954 // Next, add all of the operands to the PHI. 955 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) { 956 // We only currently try to fold the condition of a select when it is a phi, 957 // not the true/false values. 958 Value *TrueV = SI->getTrueValue(); 959 Value *FalseV = SI->getFalseValue(); 960 BasicBlock *PhiTransBB = PN->getParent(); 961 for (unsigned i = 0; i != NumPHIValues; ++i) { 962 BasicBlock *ThisBB = PN->getIncomingBlock(i); 963 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB); 964 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB); 965 Value *InV = nullptr; 966 // Beware of ConstantExpr: it may eventually evaluate to getNullValue, 967 // even if currently isNullValue gives false. 968 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)); 969 // For vector constants, we cannot use isNullValue to fold into 970 // FalseVInPred versus TrueVInPred. When we have individual nonzero 971 // elements in the vector, we will incorrectly fold InC to 972 // `TrueVInPred`. 973 if (InC && !isa<ConstantExpr>(InC) && isa<ConstantInt>(InC)) 974 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred; 975 else { 976 // Generate the select in the same block as PN's current incoming block. 977 // Note: ThisBB need not be the NonConstBB because vector constants 978 // which are constants by definition are handled here. 979 // FIXME: This can lead to an increase in IR generation because we might 980 // generate selects for vector constant phi operand, that could not be 981 // folded to TrueVInPred or FalseVInPred as done for ConstantInt. For 982 // non-vector phis, this transformation was always profitable because 983 // the select would be generated exactly once in the NonConstBB. 984 Builder.SetInsertPoint(ThisBB->getTerminator()); 985 InV = Builder.CreateSelect(PN->getIncomingValue(i), TrueVInPred, 986 FalseVInPred, "phitmp"); 987 } 988 NewPN->addIncoming(InV, ThisBB); 989 } 990 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) { 991 Constant *C = cast<Constant>(I.getOperand(1)); 992 for (unsigned i = 0; i != NumPHIValues; ++i) { 993 Value *InV = nullptr; 994 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) 995 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C); 996 else if (isa<ICmpInst>(CI)) 997 InV = Builder.CreateICmp(CI->getPredicate(), PN->getIncomingValue(i), 998 C, "phitmp"); 999 else 1000 InV = Builder.CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i), 1001 C, "phitmp"); 1002 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1003 } 1004 } else if (auto *BO = dyn_cast<BinaryOperator>(&I)) { 1005 for (unsigned i = 0; i != NumPHIValues; ++i) { 1006 Value *InV = foldOperationIntoPhiValue(BO, PN->getIncomingValue(i), 1007 Builder); 1008 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1009 } 1010 } else { 1011 CastInst *CI = cast<CastInst>(&I); 1012 Type *RetTy = CI->getType(); 1013 for (unsigned i = 0; i != NumPHIValues; ++i) { 1014 Value *InV; 1015 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) 1016 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy); 1017 else 1018 InV = Builder.CreateCast(CI->getOpcode(), PN->getIncomingValue(i), 1019 I.getType(), "phitmp"); 1020 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1021 } 1022 } 1023 1024 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) { 1025 Instruction *User = cast<Instruction>(*UI++); 1026 if (User == &I) continue; 1027 replaceInstUsesWith(*User, NewPN); 1028 eraseInstFromFunction(*User); 1029 } 1030 return replaceInstUsesWith(I, NewPN); 1031 } 1032 1033 Instruction *InstCombiner::foldBinOpIntoSelectOrPhi(BinaryOperator &I) { 1034 if (!isa<Constant>(I.getOperand(1))) 1035 return nullptr; 1036 1037 if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) { 1038 if (Instruction *NewSel = FoldOpIntoSelect(I, Sel)) 1039 return NewSel; 1040 } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) { 1041 if (Instruction *NewPhi = foldOpIntoPhi(I, PN)) 1042 return NewPhi; 1043 } 1044 return nullptr; 1045 } 1046 1047 /// Given a pointer type and a constant offset, determine whether or not there 1048 /// is a sequence of GEP indices into the pointed type that will land us at the 1049 /// specified offset. If so, fill them into NewIndices and return the resultant 1050 /// element type, otherwise return null. 1051 Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset, 1052 SmallVectorImpl<Value *> &NewIndices) { 1053 Type *Ty = PtrTy->getElementType(); 1054 if (!Ty->isSized()) 1055 return nullptr; 1056 1057 // Start with the index over the outer type. Note that the type size 1058 // might be zero (even if the offset isn't zero) if the indexed type 1059 // is something like [0 x {int, int}] 1060 Type *IndexTy = DL.getIndexType(PtrTy); 1061 int64_t FirstIdx = 0; 1062 if (int64_t TySize = DL.getTypeAllocSize(Ty)) { 1063 FirstIdx = Offset/TySize; 1064 Offset -= FirstIdx*TySize; 1065 1066 // Handle hosts where % returns negative instead of values [0..TySize). 1067 if (Offset < 0) { 1068 --FirstIdx; 1069 Offset += TySize; 1070 assert(Offset >= 0); 1071 } 1072 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset"); 1073 } 1074 1075 NewIndices.push_back(ConstantInt::get(IndexTy, FirstIdx)); 1076 1077 // Index into the types. If we fail, set OrigBase to null. 1078 while (Offset) { 1079 // Indexing into tail padding between struct/array elements. 1080 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty)) 1081 return nullptr; 1082 1083 if (StructType *STy = dyn_cast<StructType>(Ty)) { 1084 const StructLayout *SL = DL.getStructLayout(STy); 1085 assert(Offset < (int64_t)SL->getSizeInBytes() && 1086 "Offset must stay within the indexed type"); 1087 1088 unsigned Elt = SL->getElementContainingOffset(Offset); 1089 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1090 Elt)); 1091 1092 Offset -= SL->getElementOffset(Elt); 1093 Ty = STy->getElementType(Elt); 1094 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 1095 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType()); 1096 assert(EltSize && "Cannot index into a zero-sized array"); 1097 NewIndices.push_back(ConstantInt::get(IndexTy,Offset/EltSize)); 1098 Offset %= EltSize; 1099 Ty = AT->getElementType(); 1100 } else { 1101 // Otherwise, we can't index into the middle of this atomic type, bail. 1102 return nullptr; 1103 } 1104 } 1105 1106 return Ty; 1107 } 1108 1109 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) { 1110 // If this GEP has only 0 indices, it is the same pointer as 1111 // Src. If Src is not a trivial GEP too, don't combine 1112 // the indices. 1113 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() && 1114 !Src.hasOneUse()) 1115 return false; 1116 return true; 1117 } 1118 1119 /// Return a value X such that Val = X * Scale, or null if none. 1120 /// If the multiplication is known not to overflow, then NoSignedWrap is set. 1121 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) { 1122 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!"); 1123 assert(cast<IntegerType>(Val->getType())->getBitWidth() == 1124 Scale.getBitWidth() && "Scale not compatible with value!"); 1125 1126 // If Val is zero or Scale is one then Val = Val * Scale. 1127 if (match(Val, m_Zero()) || Scale == 1) { 1128 NoSignedWrap = true; 1129 return Val; 1130 } 1131 1132 // If Scale is zero then it does not divide Val. 1133 if (Scale.isMinValue()) 1134 return nullptr; 1135 1136 // Look through chains of multiplications, searching for a constant that is 1137 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4 1138 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by 1139 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore 1140 // down from Val: 1141 // 1142 // Val = M1 * X || Analysis starts here and works down 1143 // M1 = M2 * Y || Doesn't descend into terms with more 1144 // M2 = Z * 4 \/ than one use 1145 // 1146 // Then to modify a term at the bottom: 1147 // 1148 // Val = M1 * X 1149 // M1 = Z * Y || Replaced M2 with Z 1150 // 1151 // Then to work back up correcting nsw flags. 1152 1153 // Op - the term we are currently analyzing. Starts at Val then drills down. 1154 // Replaced with its descaled value before exiting from the drill down loop. 1155 Value *Op = Val; 1156 1157 // Parent - initially null, but after drilling down notes where Op came from. 1158 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the 1159 // 0'th operand of Val. 1160 std::pair<Instruction *, unsigned> Parent; 1161 1162 // Set if the transform requires a descaling at deeper levels that doesn't 1163 // overflow. 1164 bool RequireNoSignedWrap = false; 1165 1166 // Log base 2 of the scale. Negative if not a power of 2. 1167 int32_t logScale = Scale.exactLogBase2(); 1168 1169 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down 1170 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { 1171 // If Op is a constant divisible by Scale then descale to the quotient. 1172 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth. 1173 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder); 1174 if (!Remainder.isMinValue()) 1175 // Not divisible by Scale. 1176 return nullptr; 1177 // Replace with the quotient in the parent. 1178 Op = ConstantInt::get(CI->getType(), Quotient); 1179 NoSignedWrap = true; 1180 break; 1181 } 1182 1183 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) { 1184 if (BO->getOpcode() == Instruction::Mul) { 1185 // Multiplication. 1186 NoSignedWrap = BO->hasNoSignedWrap(); 1187 if (RequireNoSignedWrap && !NoSignedWrap) 1188 return nullptr; 1189 1190 // There are three cases for multiplication: multiplication by exactly 1191 // the scale, multiplication by a constant different to the scale, and 1192 // multiplication by something else. 1193 Value *LHS = BO->getOperand(0); 1194 Value *RHS = BO->getOperand(1); 1195 1196 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 1197 // Multiplication by a constant. 1198 if (CI->getValue() == Scale) { 1199 // Multiplication by exactly the scale, replace the multiplication 1200 // by its left-hand side in the parent. 1201 Op = LHS; 1202 break; 1203 } 1204 1205 // Otherwise drill down into the constant. 1206 if (!Op->hasOneUse()) 1207 return nullptr; 1208 1209 Parent = std::make_pair(BO, 1); 1210 continue; 1211 } 1212 1213 // Multiplication by something else. Drill down into the left-hand side 1214 // since that's where the reassociate pass puts the good stuff. 1215 if (!Op->hasOneUse()) 1216 return nullptr; 1217 1218 Parent = std::make_pair(BO, 0); 1219 continue; 1220 } 1221 1222 if (logScale > 0 && BO->getOpcode() == Instruction::Shl && 1223 isa<ConstantInt>(BO->getOperand(1))) { 1224 // Multiplication by a power of 2. 1225 NoSignedWrap = BO->hasNoSignedWrap(); 1226 if (RequireNoSignedWrap && !NoSignedWrap) 1227 return nullptr; 1228 1229 Value *LHS = BO->getOperand(0); 1230 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))-> 1231 getLimitedValue(Scale.getBitWidth()); 1232 // Op = LHS << Amt. 1233 1234 if (Amt == logScale) { 1235 // Multiplication by exactly the scale, replace the multiplication 1236 // by its left-hand side in the parent. 1237 Op = LHS; 1238 break; 1239 } 1240 if (Amt < logScale || !Op->hasOneUse()) 1241 return nullptr; 1242 1243 // Multiplication by more than the scale. Reduce the multiplying amount 1244 // by the scale in the parent. 1245 Parent = std::make_pair(BO, 1); 1246 Op = ConstantInt::get(BO->getType(), Amt - logScale); 1247 break; 1248 } 1249 } 1250 1251 if (!Op->hasOneUse()) 1252 return nullptr; 1253 1254 if (CastInst *Cast = dyn_cast<CastInst>(Op)) { 1255 if (Cast->getOpcode() == Instruction::SExt) { 1256 // Op is sign-extended from a smaller type, descale in the smaller type. 1257 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits(); 1258 APInt SmallScale = Scale.trunc(SmallSize); 1259 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to 1260 // descale Op as (sext Y) * Scale. In order to have 1261 // sext (Y * SmallScale) = (sext Y) * Scale 1262 // some conditions need to hold however: SmallScale must sign-extend to 1263 // Scale and the multiplication Y * SmallScale should not overflow. 1264 if (SmallScale.sext(Scale.getBitWidth()) != Scale) 1265 // SmallScale does not sign-extend to Scale. 1266 return nullptr; 1267 assert(SmallScale.exactLogBase2() == logScale); 1268 // Require that Y * SmallScale must not overflow. 1269 RequireNoSignedWrap = true; 1270 1271 // Drill down through the cast. 1272 Parent = std::make_pair(Cast, 0); 1273 Scale = SmallScale; 1274 continue; 1275 } 1276 1277 if (Cast->getOpcode() == Instruction::Trunc) { 1278 // Op is truncated from a larger type, descale in the larger type. 1279 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then 1280 // trunc (Y * sext Scale) = (trunc Y) * Scale 1281 // always holds. However (trunc Y) * Scale may overflow even if 1282 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared 1283 // from this point up in the expression (see later). 1284 if (RequireNoSignedWrap) 1285 return nullptr; 1286 1287 // Drill down through the cast. 1288 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits(); 1289 Parent = std::make_pair(Cast, 0); 1290 Scale = Scale.sext(LargeSize); 1291 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits()) 1292 logScale = -1; 1293 assert(Scale.exactLogBase2() == logScale); 1294 continue; 1295 } 1296 } 1297 1298 // Unsupported expression, bail out. 1299 return nullptr; 1300 } 1301 1302 // If Op is zero then Val = Op * Scale. 1303 if (match(Op, m_Zero())) { 1304 NoSignedWrap = true; 1305 return Op; 1306 } 1307 1308 // We know that we can successfully descale, so from here on we can safely 1309 // modify the IR. Op holds the descaled version of the deepest term in the 1310 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known 1311 // not to overflow. 1312 1313 if (!Parent.first) 1314 // The expression only had one term. 1315 return Op; 1316 1317 // Rewrite the parent using the descaled version of its operand. 1318 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!"); 1319 assert(Op != Parent.first->getOperand(Parent.second) && 1320 "Descaling was a no-op?"); 1321 Parent.first->setOperand(Parent.second, Op); 1322 Worklist.Add(Parent.first); 1323 1324 // Now work back up the expression correcting nsw flags. The logic is based 1325 // on the following observation: if X * Y is known not to overflow as a signed 1326 // multiplication, and Y is replaced by a value Z with smaller absolute value, 1327 // then X * Z will not overflow as a signed multiplication either. As we work 1328 // our way up, having NoSignedWrap 'true' means that the descaled value at the 1329 // current level has strictly smaller absolute value than the original. 1330 Instruction *Ancestor = Parent.first; 1331 do { 1332 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) { 1333 // If the multiplication wasn't nsw then we can't say anything about the 1334 // value of the descaled multiplication, and we have to clear nsw flags 1335 // from this point on up. 1336 bool OpNoSignedWrap = BO->hasNoSignedWrap(); 1337 NoSignedWrap &= OpNoSignedWrap; 1338 if (NoSignedWrap != OpNoSignedWrap) { 1339 BO->setHasNoSignedWrap(NoSignedWrap); 1340 Worklist.Add(Ancestor); 1341 } 1342 } else if (Ancestor->getOpcode() == Instruction::Trunc) { 1343 // The fact that the descaled input to the trunc has smaller absolute 1344 // value than the original input doesn't tell us anything useful about 1345 // the absolute values of the truncations. 1346 NoSignedWrap = false; 1347 } 1348 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) && 1349 "Failed to keep proper track of nsw flags while drilling down?"); 1350 1351 if (Ancestor == Val) 1352 // Got to the top, all done! 1353 return Val; 1354 1355 // Move up one level in the expression. 1356 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!"); 1357 Ancestor = Ancestor->user_back(); 1358 } while (true); 1359 } 1360 1361 Instruction *InstCombiner::foldVectorBinop(BinaryOperator &Inst) { 1362 if (!Inst.getType()->isVectorTy()) return nullptr; 1363 1364 BinaryOperator::BinaryOps Opcode = Inst.getOpcode(); 1365 unsigned NumElts = cast<VectorType>(Inst.getType())->getNumElements(); 1366 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1); 1367 assert(cast<VectorType>(LHS->getType())->getNumElements() == NumElts); 1368 assert(cast<VectorType>(RHS->getType())->getNumElements() == NumElts); 1369 1370 // If both operands of the binop are vector concatenations, then perform the 1371 // narrow binop on each pair of the source operands followed by concatenation 1372 // of the results. 1373 Value *L0, *L1, *R0, *R1; 1374 Constant *Mask; 1375 if (match(LHS, m_ShuffleVector(m_Value(L0), m_Value(L1), m_Constant(Mask))) && 1376 match(RHS, m_ShuffleVector(m_Value(R0), m_Value(R1), m_Specific(Mask))) && 1377 LHS->hasOneUse() && RHS->hasOneUse() && 1378 cast<ShuffleVectorInst>(LHS)->isConcat() && 1379 cast<ShuffleVectorInst>(RHS)->isConcat()) { 1380 // This transform does not have the speculative execution constraint as 1381 // below because the shuffle is a concatenation. The new binops are 1382 // operating on exactly the same elements as the existing binop. 1383 // TODO: We could ease the mask requirement to allow different undef lanes, 1384 // but that requires an analysis of the binop-with-undef output value. 1385 Value *NewBO0 = Builder.CreateBinOp(Opcode, L0, R0); 1386 if (auto *BO = dyn_cast<BinaryOperator>(NewBO0)) 1387 BO->copyIRFlags(&Inst); 1388 Value *NewBO1 = Builder.CreateBinOp(Opcode, L1, R1); 1389 if (auto *BO = dyn_cast<BinaryOperator>(NewBO1)) 1390 BO->copyIRFlags(&Inst); 1391 return new ShuffleVectorInst(NewBO0, NewBO1, Mask); 1392 } 1393 1394 // It may not be safe to reorder shuffles and things like div, urem, etc. 1395 // because we may trap when executing those ops on unknown vector elements. 1396 // See PR20059. 1397 if (!isSafeToSpeculativelyExecute(&Inst)) 1398 return nullptr; 1399 1400 auto createBinOpShuffle = [&](Value *X, Value *Y, Constant *M) { 1401 Value *XY = Builder.CreateBinOp(Opcode, X, Y); 1402 if (auto *BO = dyn_cast<BinaryOperator>(XY)) 1403 BO->copyIRFlags(&Inst); 1404 return new ShuffleVectorInst(XY, UndefValue::get(XY->getType()), M); 1405 }; 1406 1407 // If both arguments of the binary operation are shuffles that use the same 1408 // mask and shuffle within a single vector, move the shuffle after the binop. 1409 Value *V1, *V2; 1410 if (match(LHS, m_ShuffleVector(m_Value(V1), m_Undef(), m_Constant(Mask))) && 1411 match(RHS, m_ShuffleVector(m_Value(V2), m_Undef(), m_Specific(Mask))) && 1412 V1->getType() == V2->getType() && 1413 (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) { 1414 // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask) 1415 return createBinOpShuffle(V1, V2, Mask); 1416 } 1417 1418 // If both arguments of a commutative binop are select-shuffles that use the 1419 // same mask with commuted operands, the shuffles are unnecessary. 1420 if (Inst.isCommutative() && 1421 match(LHS, m_ShuffleVector(m_Value(V1), m_Value(V2), m_Constant(Mask))) && 1422 match(RHS, m_ShuffleVector(m_Specific(V2), m_Specific(V1), 1423 m_Specific(Mask)))) { 1424 auto *LShuf = cast<ShuffleVectorInst>(LHS); 1425 auto *RShuf = cast<ShuffleVectorInst>(RHS); 1426 // TODO: Allow shuffles that contain undefs in the mask? 1427 // That is legal, but it reduces undef knowledge. 1428 // TODO: Allow arbitrary shuffles by shuffling after binop? 1429 // That might be legal, but we have to deal with poison. 1430 if (LShuf->isSelect() && !LShuf->getMask()->containsUndefElement() && 1431 RShuf->isSelect() && !RShuf->getMask()->containsUndefElement()) { 1432 // Example: 1433 // LHS = shuffle V1, V2, <0, 5, 6, 3> 1434 // RHS = shuffle V2, V1, <0, 5, 6, 3> 1435 // LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V2 1436 Instruction *NewBO = BinaryOperator::Create(Opcode, V1, V2); 1437 NewBO->copyIRFlags(&Inst); 1438 return NewBO; 1439 } 1440 } 1441 1442 // If one argument is a shuffle within one vector and the other is a constant, 1443 // try moving the shuffle after the binary operation. This canonicalization 1444 // intends to move shuffles closer to other shuffles and binops closer to 1445 // other binops, so they can be folded. It may also enable demanded elements 1446 // transforms. 1447 Constant *C; 1448 if (match(&Inst, m_c_BinOp( 1449 m_OneUse(m_ShuffleVector(m_Value(V1), m_Undef(), m_Constant(Mask))), 1450 m_Constant(C))) && 1451 V1->getType()->getVectorNumElements() <= NumElts) { 1452 assert(Inst.getType()->getScalarType() == V1->getType()->getScalarType() && 1453 "Shuffle should not change scalar type"); 1454 1455 // Find constant NewC that has property: 1456 // shuffle(NewC, ShMask) = C 1457 // If such constant does not exist (example: ShMask=<0,0> and C=<1,2>) 1458 // reorder is not possible. A 1-to-1 mapping is not required. Example: 1459 // ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <undef,5,6,undef> 1460 bool ConstOp1 = isa<Constant>(RHS); 1461 SmallVector<int, 16> ShMask; 1462 ShuffleVectorInst::getShuffleMask(Mask, ShMask); 1463 unsigned SrcVecNumElts = V1->getType()->getVectorNumElements(); 1464 UndefValue *UndefScalar = UndefValue::get(C->getType()->getScalarType()); 1465 SmallVector<Constant *, 16> NewVecC(SrcVecNumElts, UndefScalar); 1466 bool MayChange = true; 1467 for (unsigned I = 0; I < NumElts; ++I) { 1468 Constant *CElt = C->getAggregateElement(I); 1469 if (ShMask[I] >= 0) { 1470 assert(ShMask[I] < (int)NumElts && "Not expecting narrowing shuffle"); 1471 Constant *NewCElt = NewVecC[ShMask[I]]; 1472 // Bail out if: 1473 // 1. The constant vector contains a constant expression. 1474 // 2. The shuffle needs an element of the constant vector that can't 1475 // be mapped to a new constant vector. 1476 // 3. This is a widening shuffle that copies elements of V1 into the 1477 // extended elements (extending with undef is allowed). 1478 if (!CElt || (!isa<UndefValue>(NewCElt) && NewCElt != CElt) || 1479 I >= SrcVecNumElts) { 1480 MayChange = false; 1481 break; 1482 } 1483 NewVecC[ShMask[I]] = CElt; 1484 } 1485 // If this is a widening shuffle, we must be able to extend with undef 1486 // elements. If the original binop does not produce an undef in the high 1487 // lanes, then this transform is not safe. 1488 // TODO: We could shuffle those non-undef constant values into the 1489 // result by using a constant vector (rather than an undef vector) 1490 // as operand 1 of the new binop, but that might be too aggressive 1491 // for target-independent shuffle creation. 1492 if (I >= SrcVecNumElts) { 1493 Constant *MaybeUndef = 1494 ConstOp1 ? ConstantExpr::get(Opcode, UndefScalar, CElt) 1495 : ConstantExpr::get(Opcode, CElt, UndefScalar); 1496 if (!isa<UndefValue>(MaybeUndef)) { 1497 MayChange = false; 1498 break; 1499 } 1500 } 1501 } 1502 if (MayChange) { 1503 Constant *NewC = ConstantVector::get(NewVecC); 1504 // It may not be safe to execute a binop on a vector with undef elements 1505 // because the entire instruction can be folded to undef or create poison 1506 // that did not exist in the original code. 1507 if (Inst.isIntDivRem() || (Inst.isShift() && ConstOp1)) 1508 NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1); 1509 1510 // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask) 1511 // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask) 1512 Value *NewLHS = ConstOp1 ? V1 : NewC; 1513 Value *NewRHS = ConstOp1 ? NewC : V1; 1514 return createBinOpShuffle(NewLHS, NewRHS, Mask); 1515 } 1516 } 1517 1518 return nullptr; 1519 } 1520 1521 /// Try to narrow the width of a binop if at least 1 operand is an extend of 1522 /// of a value. This requires a potentially expensive known bits check to make 1523 /// sure the narrow op does not overflow. 1524 Instruction *InstCombiner::narrowMathIfNoOverflow(BinaryOperator &BO) { 1525 // We need at least one extended operand. 1526 Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1); 1527 1528 // If this is a sub, we swap the operands since we always want an extension 1529 // on the RHS. The LHS can be an extension or a constant. 1530 if (BO.getOpcode() == Instruction::Sub) 1531 std::swap(Op0, Op1); 1532 1533 Value *X; 1534 bool IsSext = match(Op0, m_SExt(m_Value(X))); 1535 if (!IsSext && !match(Op0, m_ZExt(m_Value(X)))) 1536 return nullptr; 1537 1538 // If both operands are the same extension from the same source type and we 1539 // can eliminate at least one (hasOneUse), this might work. 1540 CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt; 1541 Value *Y; 1542 if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() && 1543 cast<Operator>(Op1)->getOpcode() == CastOpc && 1544 (Op0->hasOneUse() || Op1->hasOneUse()))) { 1545 // If that did not match, see if we have a suitable constant operand. 1546 // Truncating and extending must produce the same constant. 1547 Constant *WideC; 1548 if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC))) 1549 return nullptr; 1550 Constant *NarrowC = ConstantExpr::getTrunc(WideC, X->getType()); 1551 if (ConstantExpr::getCast(CastOpc, NarrowC, BO.getType()) != WideC) 1552 return nullptr; 1553 Y = NarrowC; 1554 } 1555 1556 // Swap back now that we found our operands. 1557 if (BO.getOpcode() == Instruction::Sub) 1558 std::swap(X, Y); 1559 1560 // Both operands have narrow versions. Last step: the math must not overflow 1561 // in the narrow width. 1562 if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext)) 1563 return nullptr; 1564 1565 // bo (ext X), (ext Y) --> ext (bo X, Y) 1566 // bo (ext X), C --> ext (bo X, C') 1567 Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow"); 1568 if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) { 1569 if (IsSext) 1570 NewBinOp->setHasNoSignedWrap(); 1571 else 1572 NewBinOp->setHasNoUnsignedWrap(); 1573 } 1574 return CastInst::Create(CastOpc, NarrowBO, BO.getType()); 1575 } 1576 1577 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) { 1578 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end()); 1579 Type *GEPType = GEP.getType(); 1580 Type *GEPEltType = GEP.getSourceElementType(); 1581 if (Value *V = SimplifyGEPInst(GEPEltType, Ops, SQ.getWithInstruction(&GEP))) 1582 return replaceInstUsesWith(GEP, V); 1583 1584 // For vector geps, use the generic demanded vector support. 1585 if (GEP.getType()->isVectorTy()) { 1586 auto VWidth = GEP.getType()->getVectorNumElements(); 1587 APInt UndefElts(VWidth, 0); 1588 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 1589 if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask, 1590 UndefElts)) { 1591 if (V != &GEP) 1592 return replaceInstUsesWith(GEP, V); 1593 return &GEP; 1594 } 1595 1596 // TODO: 1) Scalarize splat operands, 2) scalarize entire instruction if 1597 // possible (decide on canonical form for pointer broadcast), 3) exploit 1598 // undef elements to decrease demanded bits 1599 } 1600 1601 Value *PtrOp = GEP.getOperand(0); 1602 1603 // Eliminate unneeded casts for indices, and replace indices which displace 1604 // by multiples of a zero size type with zero. 1605 bool MadeChange = false; 1606 1607 // Index width may not be the same width as pointer width. 1608 // Data layout chooses the right type based on supported integer types. 1609 Type *NewScalarIndexTy = 1610 DL.getIndexType(GEP.getPointerOperandType()->getScalarType()); 1611 1612 gep_type_iterator GTI = gep_type_begin(GEP); 1613 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E; 1614 ++I, ++GTI) { 1615 // Skip indices into struct types. 1616 if (GTI.isStruct()) 1617 continue; 1618 1619 Type *IndexTy = (*I)->getType(); 1620 Type *NewIndexType = 1621 IndexTy->isVectorTy() 1622 ? VectorType::get(NewScalarIndexTy, IndexTy->getVectorNumElements()) 1623 : NewScalarIndexTy; 1624 1625 // If the element type has zero size then any index over it is equivalent 1626 // to an index of zero, so replace it with zero if it is not zero already. 1627 Type *EltTy = GTI.getIndexedType(); 1628 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0) 1629 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) { 1630 *I = Constant::getNullValue(NewIndexType); 1631 MadeChange = true; 1632 } 1633 1634 if (IndexTy != NewIndexType) { 1635 // If we are using a wider index than needed for this platform, shrink 1636 // it to what we need. If narrower, sign-extend it to what we need. 1637 // This explicit cast can make subsequent optimizations more obvious. 1638 *I = Builder.CreateIntCast(*I, NewIndexType, true); 1639 MadeChange = true; 1640 } 1641 } 1642 if (MadeChange) 1643 return &GEP; 1644 1645 // Check to see if the inputs to the PHI node are getelementptr instructions. 1646 if (auto *PN = dyn_cast<PHINode>(PtrOp)) { 1647 auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0)); 1648 if (!Op1) 1649 return nullptr; 1650 1651 // Don't fold a GEP into itself through a PHI node. This can only happen 1652 // through the back-edge of a loop. Folding a GEP into itself means that 1653 // the value of the previous iteration needs to be stored in the meantime, 1654 // thus requiring an additional register variable to be live, but not 1655 // actually achieving anything (the GEP still needs to be executed once per 1656 // loop iteration). 1657 if (Op1 == &GEP) 1658 return nullptr; 1659 1660 int DI = -1; 1661 1662 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) { 1663 auto *Op2 = dyn_cast<GetElementPtrInst>(*I); 1664 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands()) 1665 return nullptr; 1666 1667 // As for Op1 above, don't try to fold a GEP into itself. 1668 if (Op2 == &GEP) 1669 return nullptr; 1670 1671 // Keep track of the type as we walk the GEP. 1672 Type *CurTy = nullptr; 1673 1674 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) { 1675 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType()) 1676 return nullptr; 1677 1678 if (Op1->getOperand(J) != Op2->getOperand(J)) { 1679 if (DI == -1) { 1680 // We have not seen any differences yet in the GEPs feeding the 1681 // PHI yet, so we record this one if it is allowed to be a 1682 // variable. 1683 1684 // The first two arguments can vary for any GEP, the rest have to be 1685 // static for struct slots 1686 if (J > 1 && CurTy->isStructTy()) 1687 return nullptr; 1688 1689 DI = J; 1690 } else { 1691 // The GEP is different by more than one input. While this could be 1692 // extended to support GEPs that vary by more than one variable it 1693 // doesn't make sense since it greatly increases the complexity and 1694 // would result in an R+R+R addressing mode which no backend 1695 // directly supports and would need to be broken into several 1696 // simpler instructions anyway. 1697 return nullptr; 1698 } 1699 } 1700 1701 // Sink down a layer of the type for the next iteration. 1702 if (J > 0) { 1703 if (J == 1) { 1704 CurTy = Op1->getSourceElementType(); 1705 } else if (auto *CT = dyn_cast<CompositeType>(CurTy)) { 1706 CurTy = CT->getTypeAtIndex(Op1->getOperand(J)); 1707 } else { 1708 CurTy = nullptr; 1709 } 1710 } 1711 } 1712 } 1713 1714 // If not all GEPs are identical we'll have to create a new PHI node. 1715 // Check that the old PHI node has only one use so that it will get 1716 // removed. 1717 if (DI != -1 && !PN->hasOneUse()) 1718 return nullptr; 1719 1720 auto *NewGEP = cast<GetElementPtrInst>(Op1->clone()); 1721 if (DI == -1) { 1722 // All the GEPs feeding the PHI are identical. Clone one down into our 1723 // BB so that it can be merged with the current GEP. 1724 GEP.getParent()->getInstList().insert( 1725 GEP.getParent()->getFirstInsertionPt(), NewGEP); 1726 } else { 1727 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP 1728 // into the current block so it can be merged, and create a new PHI to 1729 // set that index. 1730 PHINode *NewPN; 1731 { 1732 IRBuilderBase::InsertPointGuard Guard(Builder); 1733 Builder.SetInsertPoint(PN); 1734 NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(), 1735 PN->getNumOperands()); 1736 } 1737 1738 for (auto &I : PN->operands()) 1739 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI), 1740 PN->getIncomingBlock(I)); 1741 1742 NewGEP->setOperand(DI, NewPN); 1743 GEP.getParent()->getInstList().insert( 1744 GEP.getParent()->getFirstInsertionPt(), NewGEP); 1745 NewGEP->setOperand(DI, NewPN); 1746 } 1747 1748 GEP.setOperand(0, NewGEP); 1749 PtrOp = NewGEP; 1750 } 1751 1752 // Combine Indices - If the source pointer to this getelementptr instruction 1753 // is a getelementptr instruction, combine the indices of the two 1754 // getelementptr instructions into a single instruction. 1755 if (auto *Src = dyn_cast<GEPOperator>(PtrOp)) { 1756 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src)) 1757 return nullptr; 1758 1759 // Try to reassociate loop invariant GEP chains to enable LICM. 1760 if (LI && Src->getNumOperands() == 2 && GEP.getNumOperands() == 2 && 1761 Src->hasOneUse()) { 1762 if (Loop *L = LI->getLoopFor(GEP.getParent())) { 1763 Value *GO1 = GEP.getOperand(1); 1764 Value *SO1 = Src->getOperand(1); 1765 // Reassociate the two GEPs if SO1 is variant in the loop and GO1 is 1766 // invariant: this breaks the dependence between GEPs and allows LICM 1767 // to hoist the invariant part out of the loop. 1768 if (L->isLoopInvariant(GO1) && !L->isLoopInvariant(SO1)) { 1769 // We have to be careful here. 1770 // We have something like: 1771 // %src = getelementptr <ty>, <ty>* %base, <ty> %idx 1772 // %gep = getelementptr <ty>, <ty>* %src, <ty> %idx2 1773 // If we just swap idx & idx2 then we could inadvertantly 1774 // change %src from a vector to a scalar, or vice versa. 1775 // Cases: 1776 // 1) %base a scalar & idx a scalar & idx2 a vector 1777 // => Swapping idx & idx2 turns %src into a vector type. 1778 // 2) %base a scalar & idx a vector & idx2 a scalar 1779 // => Swapping idx & idx2 turns %src in a scalar type 1780 // 3) %base, %idx, and %idx2 are scalars 1781 // => %src & %gep are scalars 1782 // => swapping idx & idx2 is safe 1783 // 4) %base a vector 1784 // => %src is a vector 1785 // => swapping idx & idx2 is safe. 1786 auto *SO0 = Src->getOperand(0); 1787 auto *SO0Ty = SO0->getType(); 1788 if (!isa<VectorType>(GEPType) || // case 3 1789 isa<VectorType>(SO0Ty)) { // case 4 1790 Src->setOperand(1, GO1); 1791 GEP.setOperand(1, SO1); 1792 return &GEP; 1793 } else { 1794 // Case 1 or 2 1795 // -- have to recreate %src & %gep 1796 // put NewSrc at same location as %src 1797 Builder.SetInsertPoint(cast<Instruction>(PtrOp)); 1798 auto *NewSrc = cast<GetElementPtrInst>( 1799 Builder.CreateGEP(GEPEltType, SO0, GO1, Src->getName())); 1800 NewSrc->setIsInBounds(Src->isInBounds()); 1801 auto *NewGEP = GetElementPtrInst::Create(GEPEltType, NewSrc, {SO1}); 1802 NewGEP->setIsInBounds(GEP.isInBounds()); 1803 return NewGEP; 1804 } 1805 } 1806 } 1807 } 1808 1809 // Note that if our source is a gep chain itself then we wait for that 1810 // chain to be resolved before we perform this transformation. This 1811 // avoids us creating a TON of code in some cases. 1812 if (auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0))) 1813 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP)) 1814 return nullptr; // Wait until our source is folded to completion. 1815 1816 SmallVector<Value*, 8> Indices; 1817 1818 // Find out whether the last index in the source GEP is a sequential idx. 1819 bool EndsWithSequential = false; 1820 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src); 1821 I != E; ++I) 1822 EndsWithSequential = I.isSequential(); 1823 1824 // Can we combine the two pointer arithmetics offsets? 1825 if (EndsWithSequential) { 1826 // Replace: gep (gep %P, long B), long A, ... 1827 // With: T = long A+B; gep %P, T, ... 1828 Value *SO1 = Src->getOperand(Src->getNumOperands()-1); 1829 Value *GO1 = GEP.getOperand(1); 1830 1831 // If they aren't the same type, then the input hasn't been processed 1832 // by the loop above yet (which canonicalizes sequential index types to 1833 // intptr_t). Just avoid transforming this until the input has been 1834 // normalized. 1835 if (SO1->getType() != GO1->getType()) 1836 return nullptr; 1837 1838 Value *Sum = 1839 SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP)); 1840 // Only do the combine when we are sure the cost after the 1841 // merge is never more than that before the merge. 1842 if (Sum == nullptr) 1843 return nullptr; 1844 1845 // Update the GEP in place if possible. 1846 if (Src->getNumOperands() == 2) { 1847 GEP.setOperand(0, Src->getOperand(0)); 1848 GEP.setOperand(1, Sum); 1849 return &GEP; 1850 } 1851 Indices.append(Src->op_begin()+1, Src->op_end()-1); 1852 Indices.push_back(Sum); 1853 Indices.append(GEP.op_begin()+2, GEP.op_end()); 1854 } else if (isa<Constant>(*GEP.idx_begin()) && 1855 cast<Constant>(*GEP.idx_begin())->isNullValue() && 1856 Src->getNumOperands() != 1) { 1857 // Otherwise we can do the fold if the first index of the GEP is a zero 1858 Indices.append(Src->op_begin()+1, Src->op_end()); 1859 Indices.append(GEP.idx_begin()+1, GEP.idx_end()); 1860 } 1861 1862 if (!Indices.empty()) 1863 return GEP.isInBounds() && Src->isInBounds() 1864 ? GetElementPtrInst::CreateInBounds( 1865 Src->getSourceElementType(), Src->getOperand(0), Indices, 1866 GEP.getName()) 1867 : GetElementPtrInst::Create(Src->getSourceElementType(), 1868 Src->getOperand(0), Indices, 1869 GEP.getName()); 1870 } 1871 1872 if (GEP.getNumIndices() == 1) { 1873 unsigned AS = GEP.getPointerAddressSpace(); 1874 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() == 1875 DL.getIndexSizeInBits(AS)) { 1876 uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType); 1877 1878 bool Matched = false; 1879 uint64_t C; 1880 Value *V = nullptr; 1881 if (TyAllocSize == 1) { 1882 V = GEP.getOperand(1); 1883 Matched = true; 1884 } else if (match(GEP.getOperand(1), 1885 m_AShr(m_Value(V), m_ConstantInt(C)))) { 1886 if (TyAllocSize == 1ULL << C) 1887 Matched = true; 1888 } else if (match(GEP.getOperand(1), 1889 m_SDiv(m_Value(V), m_ConstantInt(C)))) { 1890 if (TyAllocSize == C) 1891 Matched = true; 1892 } 1893 1894 if (Matched) { 1895 // Canonicalize (gep i8* X, -(ptrtoint Y)) 1896 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y))) 1897 // The GEP pattern is emitted by the SCEV expander for certain kinds of 1898 // pointer arithmetic. 1899 if (match(V, m_Neg(m_PtrToInt(m_Value())))) { 1900 Operator *Index = cast<Operator>(V); 1901 Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->getType()); 1902 Value *NewSub = Builder.CreateSub(PtrToInt, Index->getOperand(1)); 1903 return CastInst::Create(Instruction::IntToPtr, NewSub, GEPType); 1904 } 1905 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) 1906 // to (bitcast Y) 1907 Value *Y; 1908 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)), 1909 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) 1910 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y, GEPType); 1911 } 1912 } 1913 } 1914 1915 // We do not handle pointer-vector geps here. 1916 if (GEPType->isVectorTy()) 1917 return nullptr; 1918 1919 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0). 1920 Value *StrippedPtr = PtrOp->stripPointerCasts(); 1921 PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType()); 1922 1923 if (StrippedPtr != PtrOp) { 1924 bool HasZeroPointerIndex = false; 1925 Type *StrippedPtrEltTy = StrippedPtrTy->getElementType(); 1926 1927 if (auto *C = dyn_cast<ConstantInt>(GEP.getOperand(1))) 1928 HasZeroPointerIndex = C->isZero(); 1929 1930 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... 1931 // into : GEP [10 x i8]* X, i32 0, ... 1932 // 1933 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ... 1934 // into : GEP i8* X, ... 1935 // 1936 // This occurs when the program declares an array extern like "int X[];" 1937 if (HasZeroPointerIndex) { 1938 if (auto *CATy = dyn_cast<ArrayType>(GEPEltType)) { 1939 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ? 1940 if (CATy->getElementType() == StrippedPtrEltTy) { 1941 // -> GEP i8* X, ... 1942 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end()); 1943 GetElementPtrInst *Res = GetElementPtrInst::Create( 1944 StrippedPtrEltTy, StrippedPtr, Idx, GEP.getName()); 1945 Res->setIsInBounds(GEP.isInBounds()); 1946 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) 1947 return Res; 1948 // Insert Res, and create an addrspacecast. 1949 // e.g., 1950 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ... 1951 // -> 1952 // %0 = GEP i8 addrspace(1)* X, ... 1953 // addrspacecast i8 addrspace(1)* %0 to i8* 1954 return new AddrSpaceCastInst(Builder.Insert(Res), GEPType); 1955 } 1956 1957 if (auto *XATy = dyn_cast<ArrayType>(StrippedPtrEltTy)) { 1958 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ? 1959 if (CATy->getElementType() == XATy->getElementType()) { 1960 // -> GEP [10 x i8]* X, i32 0, ... 1961 // At this point, we know that the cast source type is a pointer 1962 // to an array of the same type as the destination pointer 1963 // array. Because the array type is never stepped over (there 1964 // is a leading zero) we can fold the cast into this GEP. 1965 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) { 1966 GEP.setOperand(0, StrippedPtr); 1967 GEP.setSourceElementType(XATy); 1968 return &GEP; 1969 } 1970 // Cannot replace the base pointer directly because StrippedPtr's 1971 // address space is different. Instead, create a new GEP followed by 1972 // an addrspacecast. 1973 // e.g., 1974 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*), 1975 // i32 0, ... 1976 // -> 1977 // %0 = GEP [10 x i8] addrspace(1)* X, ... 1978 // addrspacecast i8 addrspace(1)* %0 to i8* 1979 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end()); 1980 Value *NewGEP = 1981 GEP.isInBounds() 1982 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 1983 Idx, GEP.getName()) 1984 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx, 1985 GEP.getName()); 1986 return new AddrSpaceCastInst(NewGEP, GEPType); 1987 } 1988 } 1989 } 1990 } else if (GEP.getNumOperands() == 2) { 1991 // Transform things like: 1992 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V 1993 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast 1994 if (StrippedPtrEltTy->isArrayTy() && 1995 DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()) == 1996 DL.getTypeAllocSize(GEPEltType)) { 1997 Type *IdxType = DL.getIndexType(GEPType); 1998 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) }; 1999 Value *NewGEP = 2000 GEP.isInBounds() 2001 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, Idx, 2002 GEP.getName()) 2003 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx, 2004 GEP.getName()); 2005 2006 // V and GEP are both pointer types --> BitCast 2007 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, GEPType); 2008 } 2009 2010 // Transform things like: 2011 // %V = mul i64 %N, 4 2012 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V 2013 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast 2014 if (GEPEltType->isSized() && StrippedPtrEltTy->isSized()) { 2015 // Check that changing the type amounts to dividing the index by a scale 2016 // factor. 2017 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType); 2018 uint64_t SrcSize = DL.getTypeAllocSize(StrippedPtrEltTy); 2019 if (ResSize && SrcSize % ResSize == 0) { 2020 Value *Idx = GEP.getOperand(1); 2021 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits(); 2022 uint64_t Scale = SrcSize / ResSize; 2023 2024 // Earlier transforms ensure that the index has the right type 2025 // according to Data Layout, which considerably simplifies the 2026 // logic by eliminating implicit casts. 2027 assert(Idx->getType() == DL.getIndexType(GEPType) && 2028 "Index type does not match the Data Layout preferences"); 2029 2030 bool NSW; 2031 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) { 2032 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP. 2033 // If the multiplication NewIdx * Scale may overflow then the new 2034 // GEP may not be "inbounds". 2035 Value *NewGEP = 2036 GEP.isInBounds() && NSW 2037 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 2038 NewIdx, GEP.getName()) 2039 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, NewIdx, 2040 GEP.getName()); 2041 2042 // The NewGEP must be pointer typed, so must the old one -> BitCast 2043 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, 2044 GEPType); 2045 } 2046 } 2047 } 2048 2049 // Similarly, transform things like: 2050 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp 2051 // (where tmp = 8*tmp2) into: 2052 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast 2053 if (GEPEltType->isSized() && StrippedPtrEltTy->isSized() && 2054 StrippedPtrEltTy->isArrayTy()) { 2055 // Check that changing to the array element type amounts to dividing the 2056 // index by a scale factor. 2057 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType); 2058 uint64_t ArrayEltSize = 2059 DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()); 2060 if (ResSize && ArrayEltSize % ResSize == 0) { 2061 Value *Idx = GEP.getOperand(1); 2062 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits(); 2063 uint64_t Scale = ArrayEltSize / ResSize; 2064 2065 // Earlier transforms ensure that the index has the right type 2066 // according to the Data Layout, which considerably simplifies 2067 // the logic by eliminating implicit casts. 2068 assert(Idx->getType() == DL.getIndexType(GEPType) && 2069 "Index type does not match the Data Layout preferences"); 2070 2071 bool NSW; 2072 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) { 2073 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP. 2074 // If the multiplication NewIdx * Scale may overflow then the new 2075 // GEP may not be "inbounds". 2076 Type *IndTy = DL.getIndexType(GEPType); 2077 Value *Off[2] = {Constant::getNullValue(IndTy), NewIdx}; 2078 2079 Value *NewGEP = 2080 GEP.isInBounds() && NSW 2081 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 2082 Off, GEP.getName()) 2083 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Off, 2084 GEP.getName()); 2085 // The NewGEP must be pointer typed, so must the old one -> BitCast 2086 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, 2087 GEPType); 2088 } 2089 } 2090 } 2091 } 2092 } 2093 2094 // addrspacecast between types is canonicalized as a bitcast, then an 2095 // addrspacecast. To take advantage of the below bitcast + struct GEP, look 2096 // through the addrspacecast. 2097 Value *ASCStrippedPtrOp = PtrOp; 2098 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) { 2099 // X = bitcast A addrspace(1)* to B addrspace(1)* 2100 // Y = addrspacecast A addrspace(1)* to B addrspace(2)* 2101 // Z = gep Y, <...constant indices...> 2102 // Into an addrspacecasted GEP of the struct. 2103 if (auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0))) 2104 ASCStrippedPtrOp = BC; 2105 } 2106 2107 if (auto *BCI = dyn_cast<BitCastInst>(ASCStrippedPtrOp)) { 2108 Value *SrcOp = BCI->getOperand(0); 2109 PointerType *SrcType = cast<PointerType>(BCI->getSrcTy()); 2110 Type *SrcEltType = SrcType->getElementType(); 2111 2112 // GEP directly using the source operand if this GEP is accessing an element 2113 // of a bitcasted pointer to vector or array of the same dimensions: 2114 // gep (bitcast <c x ty>* X to [c x ty]*), Y, Z --> gep X, Y, Z 2115 // gep (bitcast [c x ty]* X to <c x ty>*), Y, Z --> gep X, Y, Z 2116 auto areMatchingArrayAndVecTypes = [](Type *ArrTy, Type *VecTy) { 2117 return ArrTy->getArrayElementType() == VecTy->getVectorElementType() && 2118 ArrTy->getArrayNumElements() == VecTy->getVectorNumElements(); 2119 }; 2120 if (GEP.getNumOperands() == 3 && 2121 ((GEPEltType->isArrayTy() && SrcEltType->isVectorTy() && 2122 areMatchingArrayAndVecTypes(GEPEltType, SrcEltType)) || 2123 (GEPEltType->isVectorTy() && SrcEltType->isArrayTy() && 2124 areMatchingArrayAndVecTypes(SrcEltType, GEPEltType)))) { 2125 2126 // Create a new GEP here, as using `setOperand()` followed by 2127 // `setSourceElementType()` won't actually update the type of the 2128 // existing GEP Value. Causing issues if this Value is accessed when 2129 // constructing an AddrSpaceCastInst 2130 Value *NGEP = 2131 GEP.isInBounds() 2132 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]}) 2133 : Builder.CreateGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]}); 2134 NGEP->takeName(&GEP); 2135 2136 // Preserve GEP address space to satisfy users 2137 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace()) 2138 return new AddrSpaceCastInst(NGEP, GEPType); 2139 2140 return replaceInstUsesWith(GEP, NGEP); 2141 } 2142 2143 // See if we can simplify: 2144 // X = bitcast A* to B* 2145 // Y = gep X, <...constant indices...> 2146 // into a gep of the original struct. This is important for SROA and alias 2147 // analysis of unions. If "A" is also a bitcast, wait for A/X to be merged. 2148 unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType); 2149 APInt Offset(OffsetBits, 0); 2150 if (!isa<BitCastInst>(SrcOp) && GEP.accumulateConstantOffset(DL, Offset)) { 2151 // If this GEP instruction doesn't move the pointer, just replace the GEP 2152 // with a bitcast of the real input to the dest type. 2153 if (!Offset) { 2154 // If the bitcast is of an allocation, and the allocation will be 2155 // converted to match the type of the cast, don't touch this. 2156 if (isa<AllocaInst>(SrcOp) || isAllocationFn(SrcOp, &TLI)) { 2157 // See if the bitcast simplifies, if so, don't nuke this GEP yet. 2158 if (Instruction *I = visitBitCast(*BCI)) { 2159 if (I != BCI) { 2160 I->takeName(BCI); 2161 BCI->getParent()->getInstList().insert(BCI->getIterator(), I); 2162 replaceInstUsesWith(*BCI, I); 2163 } 2164 return &GEP; 2165 } 2166 } 2167 2168 if (SrcType->getPointerAddressSpace() != GEP.getAddressSpace()) 2169 return new AddrSpaceCastInst(SrcOp, GEPType); 2170 return new BitCastInst(SrcOp, GEPType); 2171 } 2172 2173 // Otherwise, if the offset is non-zero, we need to find out if there is a 2174 // field at Offset in 'A's type. If so, we can pull the cast through the 2175 // GEP. 2176 SmallVector<Value*, 8> NewIndices; 2177 if (FindElementAtOffset(SrcType, Offset.getSExtValue(), NewIndices)) { 2178 Value *NGEP = 2179 GEP.isInBounds() 2180 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, NewIndices) 2181 : Builder.CreateGEP(SrcEltType, SrcOp, NewIndices); 2182 2183 if (NGEP->getType() == GEPType) 2184 return replaceInstUsesWith(GEP, NGEP); 2185 NGEP->takeName(&GEP); 2186 2187 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace()) 2188 return new AddrSpaceCastInst(NGEP, GEPType); 2189 return new BitCastInst(NGEP, GEPType); 2190 } 2191 } 2192 } 2193 2194 if (!GEP.isInBounds()) { 2195 unsigned IdxWidth = 2196 DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace()); 2197 APInt BasePtrOffset(IdxWidth, 0); 2198 Value *UnderlyingPtrOp = 2199 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL, 2200 BasePtrOffset); 2201 if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) { 2202 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) && 2203 BasePtrOffset.isNonNegative()) { 2204 APInt AllocSize(IdxWidth, DL.getTypeAllocSize(AI->getAllocatedType())); 2205 if (BasePtrOffset.ule(AllocSize)) { 2206 return GetElementPtrInst::CreateInBounds( 2207 GEP.getSourceElementType(), PtrOp, makeArrayRef(Ops).slice(1), 2208 GEP.getName()); 2209 } 2210 } 2211 } 2212 } 2213 2214 return nullptr; 2215 } 2216 2217 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI, 2218 Instruction *AI) { 2219 if (isa<ConstantPointerNull>(V)) 2220 return true; 2221 if (auto *LI = dyn_cast<LoadInst>(V)) 2222 return isa<GlobalVariable>(LI->getPointerOperand()); 2223 // Two distinct allocations will never be equal. 2224 // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking 2225 // through bitcasts of V can cause 2226 // the result statement below to be true, even when AI and V (ex: 2227 // i8* ->i32* ->i8* of AI) are the same allocations. 2228 return isAllocLikeFn(V, TLI) && V != AI; 2229 } 2230 2231 static bool isAllocSiteRemovable(Instruction *AI, 2232 SmallVectorImpl<WeakTrackingVH> &Users, 2233 const TargetLibraryInfo *TLI) { 2234 SmallVector<Instruction*, 4> Worklist; 2235 Worklist.push_back(AI); 2236 2237 do { 2238 Instruction *PI = Worklist.pop_back_val(); 2239 for (User *U : PI->users()) { 2240 Instruction *I = cast<Instruction>(U); 2241 switch (I->getOpcode()) { 2242 default: 2243 // Give up the moment we see something we can't handle. 2244 return false; 2245 2246 case Instruction::AddrSpaceCast: 2247 case Instruction::BitCast: 2248 case Instruction::GetElementPtr: 2249 Users.emplace_back(I); 2250 Worklist.push_back(I); 2251 continue; 2252 2253 case Instruction::ICmp: { 2254 ICmpInst *ICI = cast<ICmpInst>(I); 2255 // We can fold eq/ne comparisons with null to false/true, respectively. 2256 // We also fold comparisons in some conditions provided the alloc has 2257 // not escaped (see isNeverEqualToUnescapedAlloc). 2258 if (!ICI->isEquality()) 2259 return false; 2260 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0; 2261 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI)) 2262 return false; 2263 Users.emplace_back(I); 2264 continue; 2265 } 2266 2267 case Instruction::Call: 2268 // Ignore no-op and store intrinsics. 2269 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 2270 switch (II->getIntrinsicID()) { 2271 default: 2272 return false; 2273 2274 case Intrinsic::memmove: 2275 case Intrinsic::memcpy: 2276 case Intrinsic::memset: { 2277 MemIntrinsic *MI = cast<MemIntrinsic>(II); 2278 if (MI->isVolatile() || MI->getRawDest() != PI) 2279 return false; 2280 LLVM_FALLTHROUGH; 2281 } 2282 case Intrinsic::invariant_start: 2283 case Intrinsic::invariant_end: 2284 case Intrinsic::lifetime_start: 2285 case Intrinsic::lifetime_end: 2286 case Intrinsic::objectsize: 2287 Users.emplace_back(I); 2288 continue; 2289 } 2290 } 2291 2292 if (isFreeCall(I, TLI)) { 2293 Users.emplace_back(I); 2294 continue; 2295 } 2296 return false; 2297 2298 case Instruction::Store: { 2299 StoreInst *SI = cast<StoreInst>(I); 2300 if (SI->isVolatile() || SI->getPointerOperand() != PI) 2301 return false; 2302 Users.emplace_back(I); 2303 continue; 2304 } 2305 } 2306 llvm_unreachable("missing a return?"); 2307 } 2308 } while (!Worklist.empty()); 2309 return true; 2310 } 2311 2312 Instruction *InstCombiner::visitAllocSite(Instruction &MI) { 2313 // If we have a malloc call which is only used in any amount of comparisons to 2314 // null and free calls, delete the calls and replace the comparisons with true 2315 // or false as appropriate. 2316 2317 // This is based on the principle that we can substitute our own allocation 2318 // function (which will never return null) rather than knowledge of the 2319 // specific function being called. In some sense this can change the permitted 2320 // outputs of a program (when we convert a malloc to an alloca, the fact that 2321 // the allocation is now on the stack is potentially visible, for example), 2322 // but we believe in a permissible manner. 2323 SmallVector<WeakTrackingVH, 64> Users; 2324 2325 // If we are removing an alloca with a dbg.declare, insert dbg.value calls 2326 // before each store. 2327 TinyPtrVector<DbgVariableIntrinsic *> DIIs; 2328 std::unique_ptr<DIBuilder> DIB; 2329 if (isa<AllocaInst>(MI)) { 2330 DIIs = FindDbgAddrUses(&MI); 2331 DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false)); 2332 } 2333 2334 if (isAllocSiteRemovable(&MI, Users, &TLI)) { 2335 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 2336 // Lowering all @llvm.objectsize calls first because they may 2337 // use a bitcast/GEP of the alloca we are removing. 2338 if (!Users[i]) 2339 continue; 2340 2341 Instruction *I = cast<Instruction>(&*Users[i]); 2342 2343 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 2344 if (II->getIntrinsicID() == Intrinsic::objectsize) { 2345 Value *Result = 2346 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/true); 2347 replaceInstUsesWith(*I, Result); 2348 eraseInstFromFunction(*I); 2349 Users[i] = nullptr; // Skip examining in the next loop. 2350 } 2351 } 2352 } 2353 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 2354 if (!Users[i]) 2355 continue; 2356 2357 Instruction *I = cast<Instruction>(&*Users[i]); 2358 2359 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) { 2360 replaceInstUsesWith(*C, 2361 ConstantInt::get(Type::getInt1Ty(C->getContext()), 2362 C->isFalseWhenEqual())); 2363 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I) || 2364 isa<AddrSpaceCastInst>(I)) { 2365 replaceInstUsesWith(*I, UndefValue::get(I->getType())); 2366 } else if (auto *SI = dyn_cast<StoreInst>(I)) { 2367 for (auto *DII : DIIs) 2368 ConvertDebugDeclareToDebugValue(DII, SI, *DIB); 2369 } 2370 eraseInstFromFunction(*I); 2371 } 2372 2373 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) { 2374 // Replace invoke with a NOP intrinsic to maintain the original CFG 2375 Module *M = II->getModule(); 2376 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing); 2377 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(), 2378 None, "", II->getParent()); 2379 } 2380 2381 for (auto *DII : DIIs) 2382 eraseInstFromFunction(*DII); 2383 2384 return eraseInstFromFunction(MI); 2385 } 2386 return nullptr; 2387 } 2388 2389 /// Move the call to free before a NULL test. 2390 /// 2391 /// Check if this free is accessed after its argument has been test 2392 /// against NULL (property 0). 2393 /// If yes, it is legal to move this call in its predecessor block. 2394 /// 2395 /// The move is performed only if the block containing the call to free 2396 /// will be removed, i.e.: 2397 /// 1. it has only one predecessor P, and P has two successors 2398 /// 2. it contains the call, noops, and an unconditional branch 2399 /// 3. its successor is the same as its predecessor's successor 2400 /// 2401 /// The profitability is out-of concern here and this function should 2402 /// be called only if the caller knows this transformation would be 2403 /// profitable (e.g., for code size). 2404 static Instruction *tryToMoveFreeBeforeNullTest(CallInst &FI, 2405 const DataLayout &DL) { 2406 Value *Op = FI.getArgOperand(0); 2407 BasicBlock *FreeInstrBB = FI.getParent(); 2408 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor(); 2409 2410 // Validate part of constraint #1: Only one predecessor 2411 // FIXME: We can extend the number of predecessor, but in that case, we 2412 // would duplicate the call to free in each predecessor and it may 2413 // not be profitable even for code size. 2414 if (!PredBB) 2415 return nullptr; 2416 2417 // Validate constraint #2: Does this block contains only the call to 2418 // free, noops, and an unconditional branch? 2419 BasicBlock *SuccBB; 2420 Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator(); 2421 if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB))) 2422 return nullptr; 2423 2424 // If there are only 2 instructions in the block, at this point, 2425 // this is the call to free and unconditional. 2426 // If there are more than 2 instructions, check that they are noops 2427 // i.e., they won't hurt the performance of the generated code. 2428 if (FreeInstrBB->size() != 2) { 2429 for (const Instruction &Inst : *FreeInstrBB) { 2430 if (&Inst == &FI || &Inst == FreeInstrBBTerminator) 2431 continue; 2432 auto *Cast = dyn_cast<CastInst>(&Inst); 2433 if (!Cast || !Cast->isNoopCast(DL)) 2434 return nullptr; 2435 } 2436 } 2437 // Validate the rest of constraint #1 by matching on the pred branch. 2438 Instruction *TI = PredBB->getTerminator(); 2439 BasicBlock *TrueBB, *FalseBB; 2440 ICmpInst::Predicate Pred; 2441 if (!match(TI, m_Br(m_ICmp(Pred, 2442 m_CombineOr(m_Specific(Op), 2443 m_Specific(Op->stripPointerCasts())), 2444 m_Zero()), 2445 TrueBB, FalseBB))) 2446 return nullptr; 2447 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE) 2448 return nullptr; 2449 2450 // Validate constraint #3: Ensure the null case just falls through. 2451 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB)) 2452 return nullptr; 2453 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) && 2454 "Broken CFG: missing edge from predecessor to successor"); 2455 2456 // At this point, we know that everything in FreeInstrBB can be moved 2457 // before TI. 2458 for (BasicBlock::iterator It = FreeInstrBB->begin(), End = FreeInstrBB->end(); 2459 It != End;) { 2460 Instruction &Instr = *It++; 2461 if (&Instr == FreeInstrBBTerminator) 2462 break; 2463 Instr.moveBefore(TI); 2464 } 2465 assert(FreeInstrBB->size() == 1 && 2466 "Only the branch instruction should remain"); 2467 return &FI; 2468 } 2469 2470 Instruction *InstCombiner::visitFree(CallInst &FI) { 2471 Value *Op = FI.getArgOperand(0); 2472 2473 // free undef -> unreachable. 2474 if (isa<UndefValue>(Op)) { 2475 // Insert a new store to null because we cannot modify the CFG here. 2476 Builder.CreateStore(ConstantInt::getTrue(FI.getContext()), 2477 UndefValue::get(Type::getInt1PtrTy(FI.getContext()))); 2478 return eraseInstFromFunction(FI); 2479 } 2480 2481 // If we have 'free null' delete the instruction. This can happen in stl code 2482 // when lots of inlining happens. 2483 if (isa<ConstantPointerNull>(Op)) 2484 return eraseInstFromFunction(FI); 2485 2486 // If we optimize for code size, try to move the call to free before the null 2487 // test so that simplify cfg can remove the empty block and dead code 2488 // elimination the branch. I.e., helps to turn something like: 2489 // if (foo) free(foo); 2490 // into 2491 // free(foo); 2492 if (MinimizeSize) 2493 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI, DL)) 2494 return I; 2495 2496 return nullptr; 2497 } 2498 2499 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) { 2500 if (RI.getNumOperands() == 0) // ret void 2501 return nullptr; 2502 2503 Value *ResultOp = RI.getOperand(0); 2504 Type *VTy = ResultOp->getType(); 2505 if (!VTy->isIntegerTy()) 2506 return nullptr; 2507 2508 // There might be assume intrinsics dominating this return that completely 2509 // determine the value. If so, constant fold it. 2510 KnownBits Known = computeKnownBits(ResultOp, 0, &RI); 2511 if (Known.isConstant()) 2512 RI.setOperand(0, Constant::getIntegerValue(VTy, Known.getConstant())); 2513 2514 return nullptr; 2515 } 2516 2517 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) { 2518 // Change br (not X), label True, label False to: br X, label False, True 2519 Value *X = nullptr; 2520 BasicBlock *TrueDest; 2521 BasicBlock *FalseDest; 2522 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) && 2523 !isa<Constant>(X)) { 2524 // Swap Destinations and condition... 2525 BI.setCondition(X); 2526 BI.swapSuccessors(); 2527 return &BI; 2528 } 2529 2530 // If the condition is irrelevant, remove the use so that other 2531 // transforms on the condition become more effective. 2532 if (BI.isConditional() && !isa<ConstantInt>(BI.getCondition()) && 2533 BI.getSuccessor(0) == BI.getSuccessor(1)) { 2534 BI.setCondition(ConstantInt::getFalse(BI.getCondition()->getType())); 2535 return &BI; 2536 } 2537 2538 // Canonicalize, for example, icmp_ne -> icmp_eq or fcmp_one -> fcmp_oeq. 2539 CmpInst::Predicate Pred; 2540 if (match(&BI, m_Br(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), TrueDest, 2541 FalseDest)) && 2542 !isCanonicalPredicate(Pred)) { 2543 // Swap destinations and condition. 2544 CmpInst *Cond = cast<CmpInst>(BI.getCondition()); 2545 Cond->setPredicate(CmpInst::getInversePredicate(Pred)); 2546 BI.swapSuccessors(); 2547 Worklist.Add(Cond); 2548 return &BI; 2549 } 2550 2551 return nullptr; 2552 } 2553 2554 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) { 2555 Value *Cond = SI.getCondition(); 2556 Value *Op0; 2557 ConstantInt *AddRHS; 2558 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) { 2559 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'. 2560 for (auto Case : SI.cases()) { 2561 Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS); 2562 assert(isa<ConstantInt>(NewCase) && 2563 "Result of expression should be constant"); 2564 Case.setValue(cast<ConstantInt>(NewCase)); 2565 } 2566 SI.setCondition(Op0); 2567 return &SI; 2568 } 2569 2570 KnownBits Known = computeKnownBits(Cond, 0, &SI); 2571 unsigned LeadingKnownZeros = Known.countMinLeadingZeros(); 2572 unsigned LeadingKnownOnes = Known.countMinLeadingOnes(); 2573 2574 // Compute the number of leading bits we can ignore. 2575 // TODO: A better way to determine this would use ComputeNumSignBits(). 2576 for (auto &C : SI.cases()) { 2577 LeadingKnownZeros = std::min( 2578 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros()); 2579 LeadingKnownOnes = std::min( 2580 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes()); 2581 } 2582 2583 unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes); 2584 2585 // Shrink the condition operand if the new type is smaller than the old type. 2586 // But do not shrink to a non-standard type, because backend can't generate 2587 // good code for that yet. 2588 // TODO: We can make it aggressive again after fixing PR39569. 2589 if (NewWidth > 0 && NewWidth < Known.getBitWidth() && 2590 shouldChangeType(Known.getBitWidth(), NewWidth)) { 2591 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth); 2592 Builder.SetInsertPoint(&SI); 2593 Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc"); 2594 SI.setCondition(NewCond); 2595 2596 for (auto Case : SI.cases()) { 2597 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth); 2598 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase)); 2599 } 2600 return &SI; 2601 } 2602 2603 return nullptr; 2604 } 2605 2606 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) { 2607 Value *Agg = EV.getAggregateOperand(); 2608 2609 if (!EV.hasIndices()) 2610 return replaceInstUsesWith(EV, Agg); 2611 2612 if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(), 2613 SQ.getWithInstruction(&EV))) 2614 return replaceInstUsesWith(EV, V); 2615 2616 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) { 2617 // We're extracting from an insertvalue instruction, compare the indices 2618 const unsigned *exti, *exte, *insi, *inse; 2619 for (exti = EV.idx_begin(), insi = IV->idx_begin(), 2620 exte = EV.idx_end(), inse = IV->idx_end(); 2621 exti != exte && insi != inse; 2622 ++exti, ++insi) { 2623 if (*insi != *exti) 2624 // The insert and extract both reference distinctly different elements. 2625 // This means the extract is not influenced by the insert, and we can 2626 // replace the aggregate operand of the extract with the aggregate 2627 // operand of the insert. i.e., replace 2628 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 2629 // %E = extractvalue { i32, { i32 } } %I, 0 2630 // with 2631 // %E = extractvalue { i32, { i32 } } %A, 0 2632 return ExtractValueInst::Create(IV->getAggregateOperand(), 2633 EV.getIndices()); 2634 } 2635 if (exti == exte && insi == inse) 2636 // Both iterators are at the end: Index lists are identical. Replace 2637 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 2638 // %C = extractvalue { i32, { i32 } } %B, 1, 0 2639 // with "i32 42" 2640 return replaceInstUsesWith(EV, IV->getInsertedValueOperand()); 2641 if (exti == exte) { 2642 // The extract list is a prefix of the insert list. i.e. replace 2643 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 2644 // %E = extractvalue { i32, { i32 } } %I, 1 2645 // with 2646 // %X = extractvalue { i32, { i32 } } %A, 1 2647 // %E = insertvalue { i32 } %X, i32 42, 0 2648 // by switching the order of the insert and extract (though the 2649 // insertvalue should be left in, since it may have other uses). 2650 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(), 2651 EV.getIndices()); 2652 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(), 2653 makeArrayRef(insi, inse)); 2654 } 2655 if (insi == inse) 2656 // The insert list is a prefix of the extract list 2657 // We can simply remove the common indices from the extract and make it 2658 // operate on the inserted value instead of the insertvalue result. 2659 // i.e., replace 2660 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 2661 // %E = extractvalue { i32, { i32 } } %I, 1, 0 2662 // with 2663 // %E extractvalue { i32 } { i32 42 }, 0 2664 return ExtractValueInst::Create(IV->getInsertedValueOperand(), 2665 makeArrayRef(exti, exte)); 2666 } 2667 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) { 2668 // We're extracting from an intrinsic, see if we're the only user, which 2669 // allows us to simplify multiple result intrinsics to simpler things that 2670 // just get one value. 2671 if (II->hasOneUse()) { 2672 // Check if we're grabbing the overflow bit or the result of a 'with 2673 // overflow' intrinsic. If it's the latter we can remove the intrinsic 2674 // and replace it with a traditional binary instruction. 2675 switch (II->getIntrinsicID()) { 2676 case Intrinsic::uadd_with_overflow: 2677 case Intrinsic::sadd_with_overflow: 2678 if (*EV.idx_begin() == 0) { // Normal result. 2679 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 2680 replaceInstUsesWith(*II, UndefValue::get(II->getType())); 2681 eraseInstFromFunction(*II); 2682 return BinaryOperator::CreateAdd(LHS, RHS); 2683 } 2684 2685 // If the normal result of the add is dead, and the RHS is a constant, 2686 // we can transform this into a range comparison. 2687 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3 2688 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow) 2689 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1))) 2690 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0), 2691 ConstantExpr::getNot(CI)); 2692 break; 2693 case Intrinsic::usub_with_overflow: 2694 case Intrinsic::ssub_with_overflow: 2695 if (*EV.idx_begin() == 0) { // Normal result. 2696 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 2697 replaceInstUsesWith(*II, UndefValue::get(II->getType())); 2698 eraseInstFromFunction(*II); 2699 return BinaryOperator::CreateSub(LHS, RHS); 2700 } 2701 break; 2702 case Intrinsic::umul_with_overflow: 2703 case Intrinsic::smul_with_overflow: 2704 if (*EV.idx_begin() == 0) { // Normal result. 2705 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 2706 replaceInstUsesWith(*II, UndefValue::get(II->getType())); 2707 eraseInstFromFunction(*II); 2708 return BinaryOperator::CreateMul(LHS, RHS); 2709 } 2710 break; 2711 default: 2712 break; 2713 } 2714 } 2715 } 2716 if (LoadInst *L = dyn_cast<LoadInst>(Agg)) 2717 // If the (non-volatile) load only has one use, we can rewrite this to a 2718 // load from a GEP. This reduces the size of the load. If a load is used 2719 // only by extractvalue instructions then this either must have been 2720 // optimized before, or it is a struct with padding, in which case we 2721 // don't want to do the transformation as it loses padding knowledge. 2722 if (L->isSimple() && L->hasOneUse()) { 2723 // extractvalue has integer indices, getelementptr has Value*s. Convert. 2724 SmallVector<Value*, 4> Indices; 2725 // Prefix an i32 0 since we need the first element. 2726 Indices.push_back(Builder.getInt32(0)); 2727 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end(); 2728 I != E; ++I) 2729 Indices.push_back(Builder.getInt32(*I)); 2730 2731 // We need to insert these at the location of the old load, not at that of 2732 // the extractvalue. 2733 Builder.SetInsertPoint(L); 2734 Value *GEP = Builder.CreateInBoundsGEP(L->getType(), 2735 L->getPointerOperand(), Indices); 2736 Instruction *NL = Builder.CreateLoad(EV.getType(), GEP); 2737 // Whatever aliasing information we had for the orignal load must also 2738 // hold for the smaller load, so propagate the annotations. 2739 AAMDNodes Nodes; 2740 L->getAAMetadata(Nodes); 2741 NL->setAAMetadata(Nodes); 2742 // Returning the load directly will cause the main loop to insert it in 2743 // the wrong spot, so use replaceInstUsesWith(). 2744 return replaceInstUsesWith(EV, NL); 2745 } 2746 // We could simplify extracts from other values. Note that nested extracts may 2747 // already be simplified implicitly by the above: extract (extract (insert) ) 2748 // will be translated into extract ( insert ( extract ) ) first and then just 2749 // the value inserted, if appropriate. Similarly for extracts from single-use 2750 // loads: extract (extract (load)) will be translated to extract (load (gep)) 2751 // and if again single-use then via load (gep (gep)) to load (gep). 2752 // However, double extracts from e.g. function arguments or return values 2753 // aren't handled yet. 2754 return nullptr; 2755 } 2756 2757 /// Return 'true' if the given typeinfo will match anything. 2758 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) { 2759 switch (Personality) { 2760 case EHPersonality::GNU_C: 2761 case EHPersonality::GNU_C_SjLj: 2762 case EHPersonality::Rust: 2763 // The GCC C EH and Rust personality only exists to support cleanups, so 2764 // it's not clear what the semantics of catch clauses are. 2765 return false; 2766 case EHPersonality::Unknown: 2767 return false; 2768 case EHPersonality::GNU_Ada: 2769 // While __gnat_all_others_value will match any Ada exception, it doesn't 2770 // match foreign exceptions (or didn't, before gcc-4.7). 2771 return false; 2772 case EHPersonality::GNU_CXX: 2773 case EHPersonality::GNU_CXX_SjLj: 2774 case EHPersonality::GNU_ObjC: 2775 case EHPersonality::MSVC_X86SEH: 2776 case EHPersonality::MSVC_Win64SEH: 2777 case EHPersonality::MSVC_CXX: 2778 case EHPersonality::CoreCLR: 2779 case EHPersonality::Wasm_CXX: 2780 return TypeInfo->isNullValue(); 2781 } 2782 llvm_unreachable("invalid enum"); 2783 } 2784 2785 static bool shorter_filter(const Value *LHS, const Value *RHS) { 2786 return 2787 cast<ArrayType>(LHS->getType())->getNumElements() 2788 < 2789 cast<ArrayType>(RHS->getType())->getNumElements(); 2790 } 2791 2792 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) { 2793 // The logic here should be correct for any real-world personality function. 2794 // However if that turns out not to be true, the offending logic can always 2795 // be conditioned on the personality function, like the catch-all logic is. 2796 EHPersonality Personality = 2797 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn()); 2798 2799 // Simplify the list of clauses, eg by removing repeated catch clauses 2800 // (these are often created by inlining). 2801 bool MakeNewInstruction = false; // If true, recreate using the following: 2802 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction; 2803 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup. 2804 2805 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already. 2806 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) { 2807 bool isLastClause = i + 1 == e; 2808 if (LI.isCatch(i)) { 2809 // A catch clause. 2810 Constant *CatchClause = LI.getClause(i); 2811 Constant *TypeInfo = CatchClause->stripPointerCasts(); 2812 2813 // If we already saw this clause, there is no point in having a second 2814 // copy of it. 2815 if (AlreadyCaught.insert(TypeInfo).second) { 2816 // This catch clause was not already seen. 2817 NewClauses.push_back(CatchClause); 2818 } else { 2819 // Repeated catch clause - drop the redundant copy. 2820 MakeNewInstruction = true; 2821 } 2822 2823 // If this is a catch-all then there is no point in keeping any following 2824 // clauses or marking the landingpad as having a cleanup. 2825 if (isCatchAll(Personality, TypeInfo)) { 2826 if (!isLastClause) 2827 MakeNewInstruction = true; 2828 CleanupFlag = false; 2829 break; 2830 } 2831 } else { 2832 // A filter clause. If any of the filter elements were already caught 2833 // then they can be dropped from the filter. It is tempting to try to 2834 // exploit the filter further by saying that any typeinfo that does not 2835 // occur in the filter can't be caught later (and thus can be dropped). 2836 // However this would be wrong, since typeinfos can match without being 2837 // equal (for example if one represents a C++ class, and the other some 2838 // class derived from it). 2839 assert(LI.isFilter(i) && "Unsupported landingpad clause!"); 2840 Constant *FilterClause = LI.getClause(i); 2841 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType()); 2842 unsigned NumTypeInfos = FilterType->getNumElements(); 2843 2844 // An empty filter catches everything, so there is no point in keeping any 2845 // following clauses or marking the landingpad as having a cleanup. By 2846 // dealing with this case here the following code is made a bit simpler. 2847 if (!NumTypeInfos) { 2848 NewClauses.push_back(FilterClause); 2849 if (!isLastClause) 2850 MakeNewInstruction = true; 2851 CleanupFlag = false; 2852 break; 2853 } 2854 2855 bool MakeNewFilter = false; // If true, make a new filter. 2856 SmallVector<Constant *, 16> NewFilterElts; // New elements. 2857 if (isa<ConstantAggregateZero>(FilterClause)) { 2858 // Not an empty filter - it contains at least one null typeinfo. 2859 assert(NumTypeInfos > 0 && "Should have handled empty filter already!"); 2860 Constant *TypeInfo = 2861 Constant::getNullValue(FilterType->getElementType()); 2862 // If this typeinfo is a catch-all then the filter can never match. 2863 if (isCatchAll(Personality, TypeInfo)) { 2864 // Throw the filter away. 2865 MakeNewInstruction = true; 2866 continue; 2867 } 2868 2869 // There is no point in having multiple copies of this typeinfo, so 2870 // discard all but the first copy if there is more than one. 2871 NewFilterElts.push_back(TypeInfo); 2872 if (NumTypeInfos > 1) 2873 MakeNewFilter = true; 2874 } else { 2875 ConstantArray *Filter = cast<ConstantArray>(FilterClause); 2876 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements. 2877 NewFilterElts.reserve(NumTypeInfos); 2878 2879 // Remove any filter elements that were already caught or that already 2880 // occurred in the filter. While there, see if any of the elements are 2881 // catch-alls. If so, the filter can be discarded. 2882 bool SawCatchAll = false; 2883 for (unsigned j = 0; j != NumTypeInfos; ++j) { 2884 Constant *Elt = Filter->getOperand(j); 2885 Constant *TypeInfo = Elt->stripPointerCasts(); 2886 if (isCatchAll(Personality, TypeInfo)) { 2887 // This element is a catch-all. Bail out, noting this fact. 2888 SawCatchAll = true; 2889 break; 2890 } 2891 2892 // Even if we've seen a type in a catch clause, we don't want to 2893 // remove it from the filter. An unexpected type handler may be 2894 // set up for a call site which throws an exception of the same 2895 // type caught. In order for the exception thrown by the unexpected 2896 // handler to propagate correctly, the filter must be correctly 2897 // described for the call site. 2898 // 2899 // Example: 2900 // 2901 // void unexpected() { throw 1;} 2902 // void foo() throw (int) { 2903 // std::set_unexpected(unexpected); 2904 // try { 2905 // throw 2.0; 2906 // } catch (int i) {} 2907 // } 2908 2909 // There is no point in having multiple copies of the same typeinfo in 2910 // a filter, so only add it if we didn't already. 2911 if (SeenInFilter.insert(TypeInfo).second) 2912 NewFilterElts.push_back(cast<Constant>(Elt)); 2913 } 2914 // A filter containing a catch-all cannot match anything by definition. 2915 if (SawCatchAll) { 2916 // Throw the filter away. 2917 MakeNewInstruction = true; 2918 continue; 2919 } 2920 2921 // If we dropped something from the filter, make a new one. 2922 if (NewFilterElts.size() < NumTypeInfos) 2923 MakeNewFilter = true; 2924 } 2925 if (MakeNewFilter) { 2926 FilterType = ArrayType::get(FilterType->getElementType(), 2927 NewFilterElts.size()); 2928 FilterClause = ConstantArray::get(FilterType, NewFilterElts); 2929 MakeNewInstruction = true; 2930 } 2931 2932 NewClauses.push_back(FilterClause); 2933 2934 // If the new filter is empty then it will catch everything so there is 2935 // no point in keeping any following clauses or marking the landingpad 2936 // as having a cleanup. The case of the original filter being empty was 2937 // already handled above. 2938 if (MakeNewFilter && !NewFilterElts.size()) { 2939 assert(MakeNewInstruction && "New filter but not a new instruction!"); 2940 CleanupFlag = false; 2941 break; 2942 } 2943 } 2944 } 2945 2946 // If several filters occur in a row then reorder them so that the shortest 2947 // filters come first (those with the smallest number of elements). This is 2948 // advantageous because shorter filters are more likely to match, speeding up 2949 // unwinding, but mostly because it increases the effectiveness of the other 2950 // filter optimizations below. 2951 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) { 2952 unsigned j; 2953 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters. 2954 for (j = i; j != e; ++j) 2955 if (!isa<ArrayType>(NewClauses[j]->getType())) 2956 break; 2957 2958 // Check whether the filters are already sorted by length. We need to know 2959 // if sorting them is actually going to do anything so that we only make a 2960 // new landingpad instruction if it does. 2961 for (unsigned k = i; k + 1 < j; ++k) 2962 if (shorter_filter(NewClauses[k+1], NewClauses[k])) { 2963 // Not sorted, so sort the filters now. Doing an unstable sort would be 2964 // correct too but reordering filters pointlessly might confuse users. 2965 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j, 2966 shorter_filter); 2967 MakeNewInstruction = true; 2968 break; 2969 } 2970 2971 // Look for the next batch of filters. 2972 i = j + 1; 2973 } 2974 2975 // If typeinfos matched if and only if equal, then the elements of a filter L 2976 // that occurs later than a filter F could be replaced by the intersection of 2977 // the elements of F and L. In reality two typeinfos can match without being 2978 // equal (for example if one represents a C++ class, and the other some class 2979 // derived from it) so it would be wrong to perform this transform in general. 2980 // However the transform is correct and useful if F is a subset of L. In that 2981 // case L can be replaced by F, and thus removed altogether since repeating a 2982 // filter is pointless. So here we look at all pairs of filters F and L where 2983 // L follows F in the list of clauses, and remove L if every element of F is 2984 // an element of L. This can occur when inlining C++ functions with exception 2985 // specifications. 2986 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) { 2987 // Examine each filter in turn. 2988 Value *Filter = NewClauses[i]; 2989 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType()); 2990 if (!FTy) 2991 // Not a filter - skip it. 2992 continue; 2993 unsigned FElts = FTy->getNumElements(); 2994 // Examine each filter following this one. Doing this backwards means that 2995 // we don't have to worry about filters disappearing under us when removed. 2996 for (unsigned j = NewClauses.size() - 1; j != i; --j) { 2997 Value *LFilter = NewClauses[j]; 2998 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType()); 2999 if (!LTy) 3000 // Not a filter - skip it. 3001 continue; 3002 // If Filter is a subset of LFilter, i.e. every element of Filter is also 3003 // an element of LFilter, then discard LFilter. 3004 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j; 3005 // If Filter is empty then it is a subset of LFilter. 3006 if (!FElts) { 3007 // Discard LFilter. 3008 NewClauses.erase(J); 3009 MakeNewInstruction = true; 3010 // Move on to the next filter. 3011 continue; 3012 } 3013 unsigned LElts = LTy->getNumElements(); 3014 // If Filter is longer than LFilter then it cannot be a subset of it. 3015 if (FElts > LElts) 3016 // Move on to the next filter. 3017 continue; 3018 // At this point we know that LFilter has at least one element. 3019 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros. 3020 // Filter is a subset of LFilter iff Filter contains only zeros (as we 3021 // already know that Filter is not longer than LFilter). 3022 if (isa<ConstantAggregateZero>(Filter)) { 3023 assert(FElts <= LElts && "Should have handled this case earlier!"); 3024 // Discard LFilter. 3025 NewClauses.erase(J); 3026 MakeNewInstruction = true; 3027 } 3028 // Move on to the next filter. 3029 continue; 3030 } 3031 ConstantArray *LArray = cast<ConstantArray>(LFilter); 3032 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros. 3033 // Since Filter is non-empty and contains only zeros, it is a subset of 3034 // LFilter iff LFilter contains a zero. 3035 assert(FElts > 0 && "Should have eliminated the empty filter earlier!"); 3036 for (unsigned l = 0; l != LElts; ++l) 3037 if (LArray->getOperand(l)->isNullValue()) { 3038 // LFilter contains a zero - discard it. 3039 NewClauses.erase(J); 3040 MakeNewInstruction = true; 3041 break; 3042 } 3043 // Move on to the next filter. 3044 continue; 3045 } 3046 // At this point we know that both filters are ConstantArrays. Loop over 3047 // operands to see whether every element of Filter is also an element of 3048 // LFilter. Since filters tend to be short this is probably faster than 3049 // using a method that scales nicely. 3050 ConstantArray *FArray = cast<ConstantArray>(Filter); 3051 bool AllFound = true; 3052 for (unsigned f = 0; f != FElts; ++f) { 3053 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts(); 3054 AllFound = false; 3055 for (unsigned l = 0; l != LElts; ++l) { 3056 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts(); 3057 if (LTypeInfo == FTypeInfo) { 3058 AllFound = true; 3059 break; 3060 } 3061 } 3062 if (!AllFound) 3063 break; 3064 } 3065 if (AllFound) { 3066 // Discard LFilter. 3067 NewClauses.erase(J); 3068 MakeNewInstruction = true; 3069 } 3070 // Move on to the next filter. 3071 } 3072 } 3073 3074 // If we changed any of the clauses, replace the old landingpad instruction 3075 // with a new one. 3076 if (MakeNewInstruction) { 3077 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(), 3078 NewClauses.size()); 3079 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i) 3080 NLI->addClause(NewClauses[i]); 3081 // A landing pad with no clauses must have the cleanup flag set. It is 3082 // theoretically possible, though highly unlikely, that we eliminated all 3083 // clauses. If so, force the cleanup flag to true. 3084 if (NewClauses.empty()) 3085 CleanupFlag = true; 3086 NLI->setCleanup(CleanupFlag); 3087 return NLI; 3088 } 3089 3090 // Even if none of the clauses changed, we may nonetheless have understood 3091 // that the cleanup flag is pointless. Clear it if so. 3092 if (LI.isCleanup() != CleanupFlag) { 3093 assert(!CleanupFlag && "Adding a cleanup, not removing one?!"); 3094 LI.setCleanup(CleanupFlag); 3095 return &LI; 3096 } 3097 3098 return nullptr; 3099 } 3100 3101 /// Try to move the specified instruction from its current block into the 3102 /// beginning of DestBlock, which can only happen if it's safe to move the 3103 /// instruction past all of the instructions between it and the end of its 3104 /// block. 3105 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) { 3106 assert(I->hasOneUse() && "Invariants didn't hold!"); 3107 BasicBlock *SrcBlock = I->getParent(); 3108 3109 // Cannot move control-flow-involving, volatile loads, vaarg, etc. 3110 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() || 3111 I->isTerminator()) 3112 return false; 3113 3114 // Do not sink static or dynamic alloca instructions. Static allocas must 3115 // remain in the entry block, and dynamic allocas must not be sunk in between 3116 // a stacksave / stackrestore pair, which would incorrectly shorten its 3117 // lifetime. 3118 if (isa<AllocaInst>(I)) 3119 return false; 3120 3121 // Do not sink into catchswitch blocks. 3122 if (isa<CatchSwitchInst>(DestBlock->getTerminator())) 3123 return false; 3124 3125 // Do not sink convergent call instructions. 3126 if (auto *CI = dyn_cast<CallInst>(I)) { 3127 if (CI->isConvergent()) 3128 return false; 3129 } 3130 // We can only sink load instructions if there is nothing between the load and 3131 // the end of block that could change the value. 3132 if (I->mayReadFromMemory()) { 3133 for (BasicBlock::iterator Scan = I->getIterator(), 3134 E = I->getParent()->end(); 3135 Scan != E; ++Scan) 3136 if (Scan->mayWriteToMemory()) 3137 return false; 3138 } 3139 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt(); 3140 I->moveBefore(&*InsertPos); 3141 ++NumSunkInst; 3142 3143 // Also sink all related debug uses from the source basic block. Otherwise we 3144 // get debug use before the def. Attempt to salvage debug uses first, to 3145 // maximise the range variables have location for. If we cannot salvage, then 3146 // mark the location undef: we know it was supposed to receive a new location 3147 // here, but that computation has been sunk. 3148 SmallVector<DbgVariableIntrinsic *, 2> DbgUsers; 3149 findDbgUsers(DbgUsers, I); 3150 for (auto *DII : reverse(DbgUsers)) { 3151 if (DII->getParent() == SrcBlock) { 3152 // dbg.value is in the same basic block as the sunk inst, see if we can 3153 // salvage it. Clone a new copy of the instruction: on success we need 3154 // both salvaged and unsalvaged copies. 3155 SmallVector<DbgVariableIntrinsic *, 1> TmpUser{ 3156 cast<DbgVariableIntrinsic>(DII->clone())}; 3157 3158 if (!salvageDebugInfoForDbgValues(*I, TmpUser)) { 3159 // We are unable to salvage: sink the cloned dbg.value, and mark the 3160 // original as undef, terminating any earlier variable location. 3161 LLVM_DEBUG(dbgs() << "SINK: " << *DII << '\n'); 3162 TmpUser[0]->insertBefore(&*InsertPos); 3163 Value *Undef = UndefValue::get(I->getType()); 3164 DII->setOperand(0, MetadataAsValue::get(DII->getContext(), 3165 ValueAsMetadata::get(Undef))); 3166 } else { 3167 // We successfully salvaged: place the salvaged dbg.value in the 3168 // original location, and move the unmodified dbg.value to sink with 3169 // the sunk inst. 3170 TmpUser[0]->insertBefore(DII); 3171 DII->moveBefore(&*InsertPos); 3172 } 3173 } 3174 } 3175 return true; 3176 } 3177 3178 bool InstCombiner::run() { 3179 while (!Worklist.isEmpty()) { 3180 Instruction *I = Worklist.RemoveOne(); 3181 if (I == nullptr) continue; // skip null values. 3182 3183 // Check to see if we can DCE the instruction. 3184 if (isInstructionTriviallyDead(I, &TLI)) { 3185 LLVM_DEBUG(dbgs() << "IC: DCE: " << *I << '\n'); 3186 eraseInstFromFunction(*I); 3187 ++NumDeadInst; 3188 MadeIRChange = true; 3189 continue; 3190 } 3191 3192 if (!DebugCounter::shouldExecute(VisitCounter)) 3193 continue; 3194 3195 // Instruction isn't dead, see if we can constant propagate it. 3196 if (!I->use_empty() && 3197 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) { 3198 if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) { 3199 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I 3200 << '\n'); 3201 3202 // Add operands to the worklist. 3203 replaceInstUsesWith(*I, C); 3204 ++NumConstProp; 3205 if (isInstructionTriviallyDead(I, &TLI)) 3206 eraseInstFromFunction(*I); 3207 MadeIRChange = true; 3208 continue; 3209 } 3210 } 3211 3212 // In general, it is possible for computeKnownBits to determine all bits in 3213 // a value even when the operands are not all constants. 3214 Type *Ty = I->getType(); 3215 if (ExpensiveCombines && !I->use_empty() && Ty->isIntOrIntVectorTy()) { 3216 KnownBits Known = computeKnownBits(I, /*Depth*/0, I); 3217 if (Known.isConstant()) { 3218 Constant *C = ConstantInt::get(Ty, Known.getConstant()); 3219 LLVM_DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C 3220 << " from: " << *I << '\n'); 3221 3222 // Add operands to the worklist. 3223 replaceInstUsesWith(*I, C); 3224 ++NumConstProp; 3225 if (isInstructionTriviallyDead(I, &TLI)) 3226 eraseInstFromFunction(*I); 3227 MadeIRChange = true; 3228 continue; 3229 } 3230 } 3231 3232 // See if we can trivially sink this instruction to a successor basic block. 3233 if (EnableCodeSinking && I->hasOneUse()) { 3234 BasicBlock *BB = I->getParent(); 3235 Instruction *UserInst = cast<Instruction>(*I->user_begin()); 3236 BasicBlock *UserParent; 3237 3238 // Get the block the use occurs in. 3239 if (PHINode *PN = dyn_cast<PHINode>(UserInst)) 3240 UserParent = PN->getIncomingBlock(*I->use_begin()); 3241 else 3242 UserParent = UserInst->getParent(); 3243 3244 if (UserParent != BB) { 3245 bool UserIsSuccessor = false; 3246 // See if the user is one of our successors. 3247 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) 3248 if (*SI == UserParent) { 3249 UserIsSuccessor = true; 3250 break; 3251 } 3252 3253 // If the user is one of our immediate successors, and if that successor 3254 // only has us as a predecessors (we'd have to split the critical edge 3255 // otherwise), we can keep going. 3256 if (UserIsSuccessor && UserParent->getUniquePredecessor()) { 3257 // Okay, the CFG is simple enough, try to sink this instruction. 3258 if (TryToSinkInstruction(I, UserParent)) { 3259 LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n'); 3260 MadeIRChange = true; 3261 // We'll add uses of the sunk instruction below, but since sinking 3262 // can expose opportunities for it's *operands* add them to the 3263 // worklist 3264 for (Use &U : I->operands()) 3265 if (Instruction *OpI = dyn_cast<Instruction>(U.get())) 3266 Worklist.Add(OpI); 3267 } 3268 } 3269 } 3270 } 3271 3272 // Now that we have an instruction, try combining it to simplify it. 3273 Builder.SetInsertPoint(I); 3274 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 3275 3276 #ifndef NDEBUG 3277 std::string OrigI; 3278 #endif 3279 LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str();); 3280 LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n'); 3281 3282 if (Instruction *Result = visit(*I)) { 3283 ++NumCombined; 3284 // Should we replace the old instruction with a new one? 3285 if (Result != I) { 3286 LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n' 3287 << " New = " << *Result << '\n'); 3288 3289 if (I->getDebugLoc()) 3290 Result->setDebugLoc(I->getDebugLoc()); 3291 // Everything uses the new instruction now. 3292 I->replaceAllUsesWith(Result); 3293 3294 // Move the name to the new instruction first. 3295 Result->takeName(I); 3296 3297 // Push the new instruction and any users onto the worklist. 3298 Worklist.AddUsersToWorkList(*Result); 3299 Worklist.Add(Result); 3300 3301 // Insert the new instruction into the basic block... 3302 BasicBlock *InstParent = I->getParent(); 3303 BasicBlock::iterator InsertPos = I->getIterator(); 3304 3305 // If we replace a PHI with something that isn't a PHI, fix up the 3306 // insertion point. 3307 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos)) 3308 InsertPos = InstParent->getFirstInsertionPt(); 3309 3310 InstParent->getInstList().insert(InsertPos, Result); 3311 3312 eraseInstFromFunction(*I); 3313 } else { 3314 LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n' 3315 << " New = " << *I << '\n'); 3316 3317 // If the instruction was modified, it's possible that it is now dead. 3318 // if so, remove it. 3319 if (isInstructionTriviallyDead(I, &TLI)) { 3320 eraseInstFromFunction(*I); 3321 } else { 3322 Worklist.AddUsersToWorkList(*I); 3323 Worklist.Add(I); 3324 } 3325 } 3326 MadeIRChange = true; 3327 } 3328 } 3329 3330 Worklist.Zap(); 3331 return MadeIRChange; 3332 } 3333 3334 /// Walk the function in depth-first order, adding all reachable code to the 3335 /// worklist. 3336 /// 3337 /// This has a couple of tricks to make the code faster and more powerful. In 3338 /// particular, we constant fold and DCE instructions as we go, to avoid adding 3339 /// them to the worklist (this significantly speeds up instcombine on code where 3340 /// many instructions are dead or constant). Additionally, if we find a branch 3341 /// whose condition is a known constant, we only visit the reachable successors. 3342 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL, 3343 SmallPtrSetImpl<BasicBlock *> &Visited, 3344 InstCombineWorklist &ICWorklist, 3345 const TargetLibraryInfo *TLI) { 3346 bool MadeIRChange = false; 3347 SmallVector<BasicBlock*, 256> Worklist; 3348 Worklist.push_back(BB); 3349 3350 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist; 3351 DenseMap<Constant *, Constant *> FoldedConstants; 3352 3353 do { 3354 BB = Worklist.pop_back_val(); 3355 3356 // We have now visited this block! If we've already been here, ignore it. 3357 if (!Visited.insert(BB).second) 3358 continue; 3359 3360 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) { 3361 Instruction *Inst = &*BBI++; 3362 3363 // DCE instruction if trivially dead. 3364 if (isInstructionTriviallyDead(Inst, TLI)) { 3365 ++NumDeadInst; 3366 LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n'); 3367 if (!salvageDebugInfo(*Inst)) 3368 replaceDbgUsesWithUndef(Inst); 3369 Inst->eraseFromParent(); 3370 MadeIRChange = true; 3371 continue; 3372 } 3373 3374 // ConstantProp instruction if trivially constant. 3375 if (!Inst->use_empty() && 3376 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0)))) 3377 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) { 3378 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *Inst 3379 << '\n'); 3380 Inst->replaceAllUsesWith(C); 3381 ++NumConstProp; 3382 if (isInstructionTriviallyDead(Inst, TLI)) 3383 Inst->eraseFromParent(); 3384 MadeIRChange = true; 3385 continue; 3386 } 3387 3388 // See if we can constant fold its operands. 3389 for (Use &U : Inst->operands()) { 3390 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U)) 3391 continue; 3392 3393 auto *C = cast<Constant>(U); 3394 Constant *&FoldRes = FoldedConstants[C]; 3395 if (!FoldRes) 3396 FoldRes = ConstantFoldConstant(C, DL, TLI); 3397 if (!FoldRes) 3398 FoldRes = C; 3399 3400 if (FoldRes != C) { 3401 LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst 3402 << "\n Old = " << *C 3403 << "\n New = " << *FoldRes << '\n'); 3404 U = FoldRes; 3405 MadeIRChange = true; 3406 } 3407 } 3408 3409 // Skip processing debug intrinsics in InstCombine. Processing these call instructions 3410 // consumes non-trivial amount of time and provides no value for the optimization. 3411 if (!isa<DbgInfoIntrinsic>(Inst)) 3412 InstrsForInstCombineWorklist.push_back(Inst); 3413 } 3414 3415 // Recursively visit successors. If this is a branch or switch on a 3416 // constant, only visit the reachable successor. 3417 Instruction *TI = BB->getTerminator(); 3418 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 3419 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) { 3420 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue(); 3421 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal); 3422 Worklist.push_back(ReachableBB); 3423 continue; 3424 } 3425 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 3426 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) { 3427 Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor()); 3428 continue; 3429 } 3430 } 3431 3432 for (BasicBlock *SuccBB : successors(TI)) 3433 Worklist.push_back(SuccBB); 3434 } while (!Worklist.empty()); 3435 3436 // Once we've found all of the instructions to add to instcombine's worklist, 3437 // add them in reverse order. This way instcombine will visit from the top 3438 // of the function down. This jives well with the way that it adds all uses 3439 // of instructions to the worklist after doing a transformation, thus avoiding 3440 // some N^2 behavior in pathological cases. 3441 ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist); 3442 3443 return MadeIRChange; 3444 } 3445 3446 /// Populate the IC worklist from a function, and prune any dead basic 3447 /// blocks discovered in the process. 3448 /// 3449 /// This also does basic constant propagation and other forward fixing to make 3450 /// the combiner itself run much faster. 3451 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL, 3452 TargetLibraryInfo *TLI, 3453 InstCombineWorklist &ICWorklist) { 3454 bool MadeIRChange = false; 3455 3456 // Do a depth-first traversal of the function, populate the worklist with 3457 // the reachable instructions. Ignore blocks that are not reachable. Keep 3458 // track of which blocks we visit. 3459 SmallPtrSet<BasicBlock *, 32> Visited; 3460 MadeIRChange |= 3461 AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI); 3462 3463 // Do a quick scan over the function. If we find any blocks that are 3464 // unreachable, remove any instructions inside of them. This prevents 3465 // the instcombine code from having to deal with some bad special cases. 3466 for (BasicBlock &BB : F) { 3467 if (Visited.count(&BB)) 3468 continue; 3469 3470 unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB); 3471 MadeIRChange |= NumDeadInstInBB > 0; 3472 NumDeadInst += NumDeadInstInBB; 3473 } 3474 3475 return MadeIRChange; 3476 } 3477 3478 static bool combineInstructionsOverFunction( 3479 Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA, 3480 AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT, 3481 OptimizationRemarkEmitter &ORE, bool ExpensiveCombines = true, 3482 LoopInfo *LI = nullptr) { 3483 auto &DL = F.getParent()->getDataLayout(); 3484 ExpensiveCombines |= EnableExpensiveCombines; 3485 3486 /// Builder - This is an IRBuilder that automatically inserts new 3487 /// instructions into the worklist when they are created. 3488 IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder( 3489 F.getContext(), TargetFolder(DL), 3490 IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) { 3491 Worklist.Add(I); 3492 if (match(I, m_Intrinsic<Intrinsic::assume>())) 3493 AC.registerAssumption(cast<CallInst>(I)); 3494 })); 3495 3496 // Lower dbg.declare intrinsics otherwise their value may be clobbered 3497 // by instcombiner. 3498 bool MadeIRChange = false; 3499 if (ShouldLowerDbgDeclare) 3500 MadeIRChange = LowerDbgDeclare(F); 3501 3502 // Iterate while there is work to do. 3503 int Iteration = 0; 3504 while (true) { 3505 ++Iteration; 3506 LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on " 3507 << F.getName() << "\n"); 3508 3509 MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist); 3510 3511 InstCombiner IC(Worklist, Builder, F.hasMinSize(), ExpensiveCombines, AA, 3512 AC, TLI, DT, ORE, DL, LI); 3513 IC.MaxArraySizeForCombine = MaxArraySize; 3514 3515 if (!IC.run()) 3516 break; 3517 } 3518 3519 return MadeIRChange || Iteration > 1; 3520 } 3521 3522 PreservedAnalyses InstCombinePass::run(Function &F, 3523 FunctionAnalysisManager &AM) { 3524 auto &AC = AM.getResult<AssumptionAnalysis>(F); 3525 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 3526 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 3527 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 3528 3529 auto *LI = AM.getCachedResult<LoopAnalysis>(F); 3530 3531 auto *AA = &AM.getResult<AAManager>(F); 3532 if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE, 3533 ExpensiveCombines, LI)) 3534 // No changes, all analyses are preserved. 3535 return PreservedAnalyses::all(); 3536 3537 // Mark all the analyses that instcombine updates as preserved. 3538 PreservedAnalyses PA; 3539 PA.preserveSet<CFGAnalyses>(); 3540 PA.preserve<AAManager>(); 3541 PA.preserve<BasicAA>(); 3542 PA.preserve<GlobalsAA>(); 3543 return PA; 3544 } 3545 3546 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const { 3547 AU.setPreservesCFG(); 3548 AU.addRequired<AAResultsWrapperPass>(); 3549 AU.addRequired<AssumptionCacheTracker>(); 3550 AU.addRequired<TargetLibraryInfoWrapperPass>(); 3551 AU.addRequired<DominatorTreeWrapperPass>(); 3552 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 3553 AU.addPreserved<DominatorTreeWrapperPass>(); 3554 AU.addPreserved<AAResultsWrapperPass>(); 3555 AU.addPreserved<BasicAAWrapperPass>(); 3556 AU.addPreserved<GlobalsAAWrapperPass>(); 3557 } 3558 3559 bool InstructionCombiningPass::runOnFunction(Function &F) { 3560 if (skipFunction(F)) 3561 return false; 3562 3563 // Required analyses. 3564 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 3565 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 3566 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 3567 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 3568 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 3569 3570 // Optional analyses. 3571 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>(); 3572 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr; 3573 3574 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, ORE, 3575 ExpensiveCombines, LI); 3576 } 3577 3578 char InstructionCombiningPass::ID = 0; 3579 3580 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine", 3581 "Combine redundant instructions", false, false) 3582 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 3583 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 3584 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 3585 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 3586 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 3587 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 3588 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine", 3589 "Combine redundant instructions", false, false) 3590 3591 // Initialization Routines 3592 void llvm::initializeInstCombine(PassRegistry &Registry) { 3593 initializeInstructionCombiningPassPass(Registry); 3594 } 3595 3596 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) { 3597 initializeInstructionCombiningPassPass(*unwrap(R)); 3598 } 3599 3600 FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) { 3601 return new InstructionCombiningPass(ExpensiveCombines); 3602 } 3603 3604 void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM) { 3605 unwrap(PM)->add(createInstructionCombiningPass()); 3606 } 3607