1 //===- InstCombineLoadStoreAlloca.cpp -------------------------------------===// 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 // This file implements the visit functions for load, store and alloca. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "InstCombineInternal.h" 14 #include "llvm/ADT/MapVector.h" 15 #include "llvm/ADT/SmallString.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/Analysis/Loads.h" 18 #include "llvm/Transforms/Utils/Local.h" 19 #include "llvm/IR/ConstantRange.h" 20 #include "llvm/IR/DataLayout.h" 21 #include "llvm/IR/DebugInfoMetadata.h" 22 #include "llvm/IR/IntrinsicInst.h" 23 #include "llvm/IR/LLVMContext.h" 24 #include "llvm/IR/MDBuilder.h" 25 #include "llvm/IR/PatternMatch.h" 26 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 27 using namespace llvm; 28 using namespace PatternMatch; 29 30 #define DEBUG_TYPE "instcombine" 31 32 STATISTIC(NumDeadStore, "Number of dead stores eliminated"); 33 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global"); 34 35 /// pointsToConstantGlobal - Return true if V (possibly indirectly) points to 36 /// some part of a constant global variable. This intentionally only accepts 37 /// constant expressions because we can't rewrite arbitrary instructions. 38 static bool pointsToConstantGlobal(Value *V) { 39 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 40 return GV->isConstant(); 41 42 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 43 if (CE->getOpcode() == Instruction::BitCast || 44 CE->getOpcode() == Instruction::AddrSpaceCast || 45 CE->getOpcode() == Instruction::GetElementPtr) 46 return pointsToConstantGlobal(CE->getOperand(0)); 47 } 48 return false; 49 } 50 51 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived) 52 /// pointer to an alloca. Ignore any reads of the pointer, return false if we 53 /// see any stores or other unknown uses. If we see pointer arithmetic, keep 54 /// track of whether it moves the pointer (with IsOffset) but otherwise traverse 55 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to 56 /// the alloca, and if the source pointer is a pointer to a constant global, we 57 /// can optimize this. 58 static bool 59 isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy, 60 SmallVectorImpl<Instruction *> &ToDelete) { 61 // We track lifetime intrinsics as we encounter them. If we decide to go 62 // ahead and replace the value with the global, this lets the caller quickly 63 // eliminate the markers. 64 65 SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect; 66 ValuesToInspect.emplace_back(V, false); 67 while (!ValuesToInspect.empty()) { 68 auto ValuePair = ValuesToInspect.pop_back_val(); 69 const bool IsOffset = ValuePair.second; 70 for (auto &U : ValuePair.first->uses()) { 71 auto *I = cast<Instruction>(U.getUser()); 72 73 if (auto *LI = dyn_cast<LoadInst>(I)) { 74 // Ignore non-volatile loads, they are always ok. 75 if (!LI->isSimple()) return false; 76 continue; 77 } 78 79 if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) { 80 // If uses of the bitcast are ok, we are ok. 81 ValuesToInspect.emplace_back(I, IsOffset); 82 continue; 83 } 84 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { 85 // If the GEP has all zero indices, it doesn't offset the pointer. If it 86 // doesn't, it does. 87 ValuesToInspect.emplace_back(I, IsOffset || !GEP->hasAllZeroIndices()); 88 continue; 89 } 90 91 if (auto *Call = dyn_cast<CallBase>(I)) { 92 // If this is the function being called then we treat it like a load and 93 // ignore it. 94 if (Call->isCallee(&U)) 95 continue; 96 97 unsigned DataOpNo = Call->getDataOperandNo(&U); 98 bool IsArgOperand = Call->isArgOperand(&U); 99 100 // Inalloca arguments are clobbered by the call. 101 if (IsArgOperand && Call->isInAllocaArgument(DataOpNo)) 102 return false; 103 104 // If this is a readonly/readnone call site, then we know it is just a 105 // load (but one that potentially returns the value itself), so we can 106 // ignore it if we know that the value isn't captured. 107 if (Call->onlyReadsMemory() && 108 (Call->use_empty() || Call->doesNotCapture(DataOpNo))) 109 continue; 110 111 // If this is being passed as a byval argument, the caller is making a 112 // copy, so it is only a read of the alloca. 113 if (IsArgOperand && Call->isByValArgument(DataOpNo)) 114 continue; 115 } 116 117 // Lifetime intrinsics can be handled by the caller. 118 if (I->isLifetimeStartOrEnd()) { 119 assert(I->use_empty() && "Lifetime markers have no result to use!"); 120 ToDelete.push_back(I); 121 continue; 122 } 123 124 // If this is isn't our memcpy/memmove, reject it as something we can't 125 // handle. 126 MemTransferInst *MI = dyn_cast<MemTransferInst>(I); 127 if (!MI) 128 return false; 129 130 // If the transfer is using the alloca as a source of the transfer, then 131 // ignore it since it is a load (unless the transfer is volatile). 132 if (U.getOperandNo() == 1) { 133 if (MI->isVolatile()) return false; 134 continue; 135 } 136 137 // If we already have seen a copy, reject the second one. 138 if (TheCopy) return false; 139 140 // If the pointer has been offset from the start of the alloca, we can't 141 // safely handle this. 142 if (IsOffset) return false; 143 144 // If the memintrinsic isn't using the alloca as the dest, reject it. 145 if (U.getOperandNo() != 0) return false; 146 147 // If the source of the memcpy/move is not a constant global, reject it. 148 if (!pointsToConstantGlobal(MI->getSource())) 149 return false; 150 151 // Otherwise, the transform is safe. Remember the copy instruction. 152 TheCopy = MI; 153 } 154 } 155 return true; 156 } 157 158 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only 159 /// modified by a copy from a constant global. If we can prove this, we can 160 /// replace any uses of the alloca with uses of the global directly. 161 static MemTransferInst * 162 isOnlyCopiedFromConstantGlobal(AllocaInst *AI, 163 SmallVectorImpl<Instruction *> &ToDelete) { 164 MemTransferInst *TheCopy = nullptr; 165 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete)) 166 return TheCopy; 167 return nullptr; 168 } 169 170 /// Returns true if V is dereferenceable for size of alloca. 171 static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI, 172 const DataLayout &DL) { 173 if (AI->isArrayAllocation()) 174 return false; 175 uint64_t AllocaSize = DL.getTypeStoreSize(AI->getAllocatedType()); 176 if (!AllocaSize) 177 return false; 178 return isDereferenceableAndAlignedPointer(V, Align(AI->getAlignment()), 179 APInt(64, AllocaSize), DL); 180 } 181 182 static Instruction *simplifyAllocaArraySize(InstCombiner &IC, AllocaInst &AI) { 183 // Check for array size of 1 (scalar allocation). 184 if (!AI.isArrayAllocation()) { 185 // i32 1 is the canonical array size for scalar allocations. 186 if (AI.getArraySize()->getType()->isIntegerTy(32)) 187 return nullptr; 188 189 // Canonicalize it. 190 return IC.replaceOperand(AI, 0, IC.Builder.getInt32(1)); 191 } 192 193 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1 194 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) { 195 if (C->getValue().getActiveBits() <= 64) { 196 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue()); 197 AllocaInst *New = IC.Builder.CreateAlloca(NewTy, nullptr, AI.getName()); 198 New->setAlignment(MaybeAlign(AI.getAlignment())); 199 200 // Scan to the end of the allocation instructions, to skip over a block of 201 // allocas if possible...also skip interleaved debug info 202 // 203 BasicBlock::iterator It(New); 204 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) 205 ++It; 206 207 // Now that I is pointing to the first non-allocation-inst in the block, 208 // insert our getelementptr instruction... 209 // 210 Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType()); 211 Value *NullIdx = Constant::getNullValue(IdxTy); 212 Value *Idx[2] = {NullIdx, NullIdx}; 213 Instruction *GEP = GetElementPtrInst::CreateInBounds( 214 NewTy, New, Idx, New->getName() + ".sub"); 215 IC.InsertNewInstBefore(GEP, *It); 216 217 // Now make everything use the getelementptr instead of the original 218 // allocation. 219 return IC.replaceInstUsesWith(AI, GEP); 220 } 221 } 222 223 if (isa<UndefValue>(AI.getArraySize())) 224 return IC.replaceInstUsesWith(AI, Constant::getNullValue(AI.getType())); 225 226 // Ensure that the alloca array size argument has type intptr_t, so that 227 // any casting is exposed early. 228 Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType()); 229 if (AI.getArraySize()->getType() != IntPtrTy) { 230 Value *V = IC.Builder.CreateIntCast(AI.getArraySize(), IntPtrTy, false); 231 return IC.replaceOperand(AI, 0, V); 232 } 233 234 return nullptr; 235 } 236 237 namespace { 238 // If I and V are pointers in different address space, it is not allowed to 239 // use replaceAllUsesWith since I and V have different types. A 240 // non-target-specific transformation should not use addrspacecast on V since 241 // the two address space may be disjoint depending on target. 242 // 243 // This class chases down uses of the old pointer until reaching the load 244 // instructions, then replaces the old pointer in the load instructions with 245 // the new pointer. If during the chasing it sees bitcast or GEP, it will 246 // create new bitcast or GEP with the new pointer and use them in the load 247 // instruction. 248 class PointerReplacer { 249 public: 250 PointerReplacer(InstCombiner &IC) : IC(IC) {} 251 void replacePointer(Instruction &I, Value *V); 252 253 private: 254 void findLoadAndReplace(Instruction &I); 255 void replace(Instruction *I); 256 Value *getReplacement(Value *I); 257 258 SmallVector<Instruction *, 4> Path; 259 MapVector<Value *, Value *> WorkMap; 260 InstCombiner &IC; 261 }; 262 } // end anonymous namespace 263 264 void PointerReplacer::findLoadAndReplace(Instruction &I) { 265 for (auto U : I.users()) { 266 auto *Inst = dyn_cast<Instruction>(&*U); 267 if (!Inst) 268 return; 269 LLVM_DEBUG(dbgs() << "Found pointer user: " << *U << '\n'); 270 if (isa<LoadInst>(Inst)) { 271 for (auto P : Path) 272 replace(P); 273 replace(Inst); 274 } else if (isa<GetElementPtrInst>(Inst) || isa<BitCastInst>(Inst)) { 275 Path.push_back(Inst); 276 findLoadAndReplace(*Inst); 277 Path.pop_back(); 278 } else { 279 return; 280 } 281 } 282 } 283 284 Value *PointerReplacer::getReplacement(Value *V) { 285 auto Loc = WorkMap.find(V); 286 if (Loc != WorkMap.end()) 287 return Loc->second; 288 return nullptr; 289 } 290 291 void PointerReplacer::replace(Instruction *I) { 292 if (getReplacement(I)) 293 return; 294 295 if (auto *LT = dyn_cast<LoadInst>(I)) { 296 auto *V = getReplacement(LT->getPointerOperand()); 297 assert(V && "Operand not replaced"); 298 auto *NewI = new LoadInst(I->getType(), V); 299 NewI->takeName(LT); 300 IC.InsertNewInstWith(NewI, *LT); 301 IC.replaceInstUsesWith(*LT, NewI); 302 WorkMap[LT] = NewI; 303 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { 304 auto *V = getReplacement(GEP->getPointerOperand()); 305 assert(V && "Operand not replaced"); 306 SmallVector<Value *, 8> Indices; 307 Indices.append(GEP->idx_begin(), GEP->idx_end()); 308 auto *NewI = GetElementPtrInst::Create( 309 V->getType()->getPointerElementType(), V, Indices); 310 IC.InsertNewInstWith(NewI, *GEP); 311 NewI->takeName(GEP); 312 WorkMap[GEP] = NewI; 313 } else if (auto *BC = dyn_cast<BitCastInst>(I)) { 314 auto *V = getReplacement(BC->getOperand(0)); 315 assert(V && "Operand not replaced"); 316 auto *NewT = PointerType::get(BC->getType()->getPointerElementType(), 317 V->getType()->getPointerAddressSpace()); 318 auto *NewI = new BitCastInst(V, NewT); 319 IC.InsertNewInstWith(NewI, *BC); 320 NewI->takeName(BC); 321 WorkMap[BC] = NewI; 322 } else { 323 llvm_unreachable("should never reach here"); 324 } 325 } 326 327 void PointerReplacer::replacePointer(Instruction &I, Value *V) { 328 #ifndef NDEBUG 329 auto *PT = cast<PointerType>(I.getType()); 330 auto *NT = cast<PointerType>(V->getType()); 331 assert(PT != NT && PT->getElementType() == NT->getElementType() && 332 "Invalid usage"); 333 #endif 334 WorkMap[&I] = V; 335 findLoadAndReplace(I); 336 } 337 338 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) { 339 if (auto *I = simplifyAllocaArraySize(*this, AI)) 340 return I; 341 342 if (AI.getAllocatedType()->isSized()) { 343 // If the alignment is 0 (unspecified), assign it the preferred alignment. 344 if (AI.getAlignment() == 0) 345 AI.setAlignment( 346 MaybeAlign(DL.getPrefTypeAlignment(AI.getAllocatedType()))); 347 348 // Move all alloca's of zero byte objects to the entry block and merge them 349 // together. Note that we only do this for alloca's, because malloc should 350 // allocate and return a unique pointer, even for a zero byte allocation. 351 if (DL.getTypeAllocSize(AI.getAllocatedType()).getKnownMinSize() == 0) { 352 // For a zero sized alloca there is no point in doing an array allocation. 353 // This is helpful if the array size is a complicated expression not used 354 // elsewhere. 355 if (AI.isArrayAllocation()) 356 return replaceOperand(AI, 0, 357 ConstantInt::get(AI.getArraySize()->getType(), 1)); 358 359 // Get the first instruction in the entry block. 360 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock(); 361 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg(); 362 if (FirstInst != &AI) { 363 // If the entry block doesn't start with a zero-size alloca then move 364 // this one to the start of the entry block. There is no problem with 365 // dominance as the array size was forced to a constant earlier already. 366 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst); 367 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() || 368 DL.getTypeAllocSize(EntryAI->getAllocatedType()) 369 .getKnownMinSize() != 0) { 370 AI.moveBefore(FirstInst); 371 return &AI; 372 } 373 374 // If the alignment of the entry block alloca is 0 (unspecified), 375 // assign it the preferred alignment. 376 if (EntryAI->getAlignment() == 0) 377 EntryAI->setAlignment( 378 MaybeAlign(DL.getPrefTypeAlignment(EntryAI->getAllocatedType()))); 379 // Replace this zero-sized alloca with the one at the start of the entry 380 // block after ensuring that the address will be aligned enough for both 381 // types. 382 const MaybeAlign MaxAlign( 383 std::max(EntryAI->getAlignment(), AI.getAlignment())); 384 EntryAI->setAlignment(MaxAlign); 385 if (AI.getType() != EntryAI->getType()) 386 return new BitCastInst(EntryAI, AI.getType()); 387 return replaceInstUsesWith(AI, EntryAI); 388 } 389 } 390 } 391 392 if (AI.getAlignment()) { 393 // Check to see if this allocation is only modified by a memcpy/memmove from 394 // a constant global whose alignment is equal to or exceeds that of the 395 // allocation. If this is the case, we can change all users to use 396 // the constant global instead. This is commonly produced by the CFE by 397 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A' 398 // is only subsequently read. 399 SmallVector<Instruction *, 4> ToDelete; 400 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) { 401 unsigned SourceAlign = getOrEnforceKnownAlignment( 402 Copy->getSource(), AI.getAlignment(), DL, &AI, &AC, &DT); 403 if (AI.getAlignment() <= SourceAlign && 404 isDereferenceableForAllocaSize(Copy->getSource(), &AI, DL)) { 405 LLVM_DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n'); 406 LLVM_DEBUG(dbgs() << " memcpy = " << *Copy << '\n'); 407 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i) 408 eraseInstFromFunction(*ToDelete[i]); 409 Constant *TheSrc = cast<Constant>(Copy->getSource()); 410 auto *SrcTy = TheSrc->getType(); 411 auto *DestTy = PointerType::get(AI.getType()->getPointerElementType(), 412 SrcTy->getPointerAddressSpace()); 413 Constant *Cast = 414 ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, DestTy); 415 if (AI.getType()->getPointerAddressSpace() == 416 SrcTy->getPointerAddressSpace()) { 417 Instruction *NewI = replaceInstUsesWith(AI, Cast); 418 eraseInstFromFunction(*Copy); 419 ++NumGlobalCopies; 420 return NewI; 421 } else { 422 PointerReplacer PtrReplacer(*this); 423 PtrReplacer.replacePointer(AI, Cast); 424 ++NumGlobalCopies; 425 } 426 } 427 } 428 } 429 430 // At last, use the generic allocation site handler to aggressively remove 431 // unused allocas. 432 return visitAllocSite(AI); 433 } 434 435 // Are we allowed to form a atomic load or store of this type? 436 static bool isSupportedAtomicType(Type *Ty) { 437 return Ty->isIntOrPtrTy() || Ty->isFloatingPointTy(); 438 } 439 440 /// Helper to combine a load to a new type. 441 /// 442 /// This just does the work of combining a load to a new type. It handles 443 /// metadata, etc., and returns the new instruction. The \c NewTy should be the 444 /// loaded *value* type. This will convert it to a pointer, cast the operand to 445 /// that pointer type, load it, etc. 446 /// 447 /// Note that this will create all of the instructions with whatever insert 448 /// point the \c InstCombiner currently is using. 449 LoadInst *InstCombiner::combineLoadToNewType(LoadInst &LI, Type *NewTy, 450 const Twine &Suffix) { 451 assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) && 452 "can't fold an atomic load to requested type"); 453 454 Value *Ptr = LI.getPointerOperand(); 455 unsigned AS = LI.getPointerAddressSpace(); 456 Value *NewPtr = nullptr; 457 if (!(match(Ptr, m_BitCast(m_Value(NewPtr))) && 458 NewPtr->getType()->getPointerElementType() == NewTy && 459 NewPtr->getType()->getPointerAddressSpace() == AS)) 460 NewPtr = Builder.CreateBitCast(Ptr, NewTy->getPointerTo(AS)); 461 462 // If old load did not have an explicit alignment specified, 463 // manually preserve the implied (ABI) alignment of the load. 464 // Else we may inadvertently incorrectly over-promise alignment. 465 const auto Align = 466 getDataLayout().getValueOrABITypeAlignment(LI.getAlign(), LI.getType()); 467 468 LoadInst *NewLoad = Builder.CreateAlignedLoad( 469 NewTy, NewPtr, Align, LI.isVolatile(), LI.getName() + Suffix); 470 NewLoad->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); 471 copyMetadataForLoad(*NewLoad, LI); 472 return NewLoad; 473 } 474 475 /// Combine a store to a new type. 476 /// 477 /// Returns the newly created store instruction. 478 static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) { 479 assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) && 480 "can't fold an atomic store of requested type"); 481 482 Value *Ptr = SI.getPointerOperand(); 483 unsigned AS = SI.getPointerAddressSpace(); 484 SmallVector<std::pair<unsigned, MDNode *>, 8> MD; 485 SI.getAllMetadata(MD); 486 487 StoreInst *NewStore = IC.Builder.CreateAlignedStore( 488 V, IC.Builder.CreateBitCast(Ptr, V->getType()->getPointerTo(AS)), 489 SI.getAlign(), SI.isVolatile()); 490 NewStore->setAtomic(SI.getOrdering(), SI.getSyncScopeID()); 491 for (const auto &MDPair : MD) { 492 unsigned ID = MDPair.first; 493 MDNode *N = MDPair.second; 494 // Note, essentially every kind of metadata should be preserved here! This 495 // routine is supposed to clone a store instruction changing *only its 496 // type*. The only metadata it makes sense to drop is metadata which is 497 // invalidated when the pointer type changes. This should essentially 498 // never be the case in LLVM, but we explicitly switch over only known 499 // metadata to be conservatively correct. If you are adding metadata to 500 // LLVM which pertains to stores, you almost certainly want to add it 501 // here. 502 switch (ID) { 503 case LLVMContext::MD_dbg: 504 case LLVMContext::MD_tbaa: 505 case LLVMContext::MD_prof: 506 case LLVMContext::MD_fpmath: 507 case LLVMContext::MD_tbaa_struct: 508 case LLVMContext::MD_alias_scope: 509 case LLVMContext::MD_noalias: 510 case LLVMContext::MD_nontemporal: 511 case LLVMContext::MD_mem_parallel_loop_access: 512 case LLVMContext::MD_access_group: 513 // All of these directly apply. 514 NewStore->setMetadata(ID, N); 515 break; 516 case LLVMContext::MD_invariant_load: 517 case LLVMContext::MD_nonnull: 518 case LLVMContext::MD_range: 519 case LLVMContext::MD_align: 520 case LLVMContext::MD_dereferenceable: 521 case LLVMContext::MD_dereferenceable_or_null: 522 // These don't apply for stores. 523 break; 524 } 525 } 526 527 return NewStore; 528 } 529 530 /// Returns true if instruction represent minmax pattern like: 531 /// select ((cmp load V1, load V2), V1, V2). 532 static bool isMinMaxWithLoads(Value *V, Type *&LoadTy) { 533 assert(V->getType()->isPointerTy() && "Expected pointer type."); 534 // Ignore possible ty* to ixx* bitcast. 535 V = peekThroughBitcast(V); 536 // Check that select is select ((cmp load V1, load V2), V1, V2) - minmax 537 // pattern. 538 CmpInst::Predicate Pred; 539 Instruction *L1; 540 Instruction *L2; 541 Value *LHS; 542 Value *RHS; 543 if (!match(V, m_Select(m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2)), 544 m_Value(LHS), m_Value(RHS)))) 545 return false; 546 LoadTy = L1->getType(); 547 return (match(L1, m_Load(m_Specific(LHS))) && 548 match(L2, m_Load(m_Specific(RHS)))) || 549 (match(L1, m_Load(m_Specific(RHS))) && 550 match(L2, m_Load(m_Specific(LHS)))); 551 } 552 553 /// Combine loads to match the type of their uses' value after looking 554 /// through intervening bitcasts. 555 /// 556 /// The core idea here is that if the result of a load is used in an operation, 557 /// we should load the type most conducive to that operation. For example, when 558 /// loading an integer and converting that immediately to a pointer, we should 559 /// instead directly load a pointer. 560 /// 561 /// However, this routine must never change the width of a load or the number of 562 /// loads as that would introduce a semantic change. This combine is expected to 563 /// be a semantic no-op which just allows loads to more closely model the types 564 /// of their consuming operations. 565 /// 566 /// Currently, we also refuse to change the precise type used for an atomic load 567 /// or a volatile load. This is debatable, and might be reasonable to change 568 /// later. However, it is risky in case some backend or other part of LLVM is 569 /// relying on the exact type loaded to select appropriate atomic operations. 570 static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) { 571 // FIXME: We could probably with some care handle both volatile and ordered 572 // atomic loads here but it isn't clear that this is important. 573 if (!LI.isUnordered()) 574 return nullptr; 575 576 if (LI.use_empty()) 577 return nullptr; 578 579 // swifterror values can't be bitcasted. 580 if (LI.getPointerOperand()->isSwiftError()) 581 return nullptr; 582 583 Type *Ty = LI.getType(); 584 const DataLayout &DL = IC.getDataLayout(); 585 586 // Try to canonicalize loads which are only ever stored to operate over 587 // integers instead of any other type. We only do this when the loaded type 588 // is sized and has a size exactly the same as its store size and the store 589 // size is a legal integer type. 590 // Do not perform canonicalization if minmax pattern is found (to avoid 591 // infinite loop). 592 Type *Dummy; 593 if (!Ty->isIntegerTy() && Ty->isSized() && 594 !(Ty->isVectorTy() && Ty->getVectorIsScalable()) && 595 DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) && 596 DL.typeSizeEqualsStoreSize(Ty) && 597 !DL.isNonIntegralPointerType(Ty) && 598 !isMinMaxWithLoads( 599 peekThroughBitcast(LI.getPointerOperand(), /*OneUseOnly=*/true), 600 Dummy)) { 601 if (all_of(LI.users(), [&LI](User *U) { 602 auto *SI = dyn_cast<StoreInst>(U); 603 return SI && SI->getPointerOperand() != &LI && 604 !SI->getPointerOperand()->isSwiftError(); 605 })) { 606 LoadInst *NewLoad = IC.combineLoadToNewType( 607 LI, Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty))); 608 // Replace all the stores with stores of the newly loaded value. 609 for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) { 610 auto *SI = cast<StoreInst>(*UI++); 611 IC.Builder.SetInsertPoint(SI); 612 combineStoreToNewValue(IC, *SI, NewLoad); 613 IC.eraseInstFromFunction(*SI); 614 } 615 assert(LI.use_empty() && "Failed to remove all users of the load!"); 616 // Return the old load so the combiner can delete it safely. 617 return &LI; 618 } 619 } 620 621 // Fold away bit casts of the loaded value by loading the desired type. 622 // We can do this for BitCastInsts as well as casts from and to pointer types, 623 // as long as those are noops (i.e., the source or dest type have the same 624 // bitwidth as the target's pointers). 625 if (LI.hasOneUse()) 626 if (auto* CI = dyn_cast<CastInst>(LI.user_back())) 627 if (CI->isNoopCast(DL)) 628 if (!LI.isAtomic() || isSupportedAtomicType(CI->getDestTy())) { 629 LoadInst *NewLoad = IC.combineLoadToNewType(LI, CI->getDestTy()); 630 CI->replaceAllUsesWith(NewLoad); 631 IC.eraseInstFromFunction(*CI); 632 return &LI; 633 } 634 635 // FIXME: We should also canonicalize loads of vectors when their elements are 636 // cast to other types. 637 return nullptr; 638 } 639 640 static Instruction *unpackLoadToAggregate(InstCombiner &IC, LoadInst &LI) { 641 // FIXME: We could probably with some care handle both volatile and atomic 642 // stores here but it isn't clear that this is important. 643 if (!LI.isSimple()) 644 return nullptr; 645 646 Type *T = LI.getType(); 647 if (!T->isAggregateType()) 648 return nullptr; 649 650 StringRef Name = LI.getName(); 651 assert(LI.getAlignment() && "Alignment must be set at this point"); 652 653 if (auto *ST = dyn_cast<StructType>(T)) { 654 // If the struct only have one element, we unpack. 655 auto NumElements = ST->getNumElements(); 656 if (NumElements == 1) { 657 LoadInst *NewLoad = IC.combineLoadToNewType(LI, ST->getTypeAtIndex(0U), 658 ".unpack"); 659 AAMDNodes AAMD; 660 LI.getAAMetadata(AAMD); 661 NewLoad->setAAMetadata(AAMD); 662 return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue( 663 UndefValue::get(T), NewLoad, 0, Name)); 664 } 665 666 // We don't want to break loads with padding here as we'd loose 667 // the knowledge that padding exists for the rest of the pipeline. 668 const DataLayout &DL = IC.getDataLayout(); 669 auto *SL = DL.getStructLayout(ST); 670 if (SL->hasPadding()) 671 return nullptr; 672 673 const auto Align = DL.getValueOrABITypeAlignment(LI.getAlign(), ST); 674 675 auto *Addr = LI.getPointerOperand(); 676 auto *IdxType = Type::getInt32Ty(T->getContext()); 677 auto *Zero = ConstantInt::get(IdxType, 0); 678 679 Value *V = UndefValue::get(T); 680 for (unsigned i = 0; i < NumElements; i++) { 681 Value *Indices[2] = { 682 Zero, 683 ConstantInt::get(IdxType, i), 684 }; 685 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices), 686 Name + ".elt"); 687 auto *L = IC.Builder.CreateAlignedLoad( 688 ST->getElementType(i), Ptr, 689 commonAlignment(Align, SL->getElementOffset(i)), Name + ".unpack"); 690 // Propagate AA metadata. It'll still be valid on the narrowed load. 691 AAMDNodes AAMD; 692 LI.getAAMetadata(AAMD); 693 L->setAAMetadata(AAMD); 694 V = IC.Builder.CreateInsertValue(V, L, i); 695 } 696 697 V->setName(Name); 698 return IC.replaceInstUsesWith(LI, V); 699 } 700 701 if (auto *AT = dyn_cast<ArrayType>(T)) { 702 auto *ET = AT->getElementType(); 703 auto NumElements = AT->getNumElements(); 704 if (NumElements == 1) { 705 LoadInst *NewLoad = IC.combineLoadToNewType(LI, ET, ".unpack"); 706 AAMDNodes AAMD; 707 LI.getAAMetadata(AAMD); 708 NewLoad->setAAMetadata(AAMD); 709 return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue( 710 UndefValue::get(T), NewLoad, 0, Name)); 711 } 712 713 // Bail out if the array is too large. Ideally we would like to optimize 714 // arrays of arbitrary size but this has a terrible impact on compile time. 715 // The threshold here is chosen arbitrarily, maybe needs a little bit of 716 // tuning. 717 if (NumElements > IC.MaxArraySizeForCombine) 718 return nullptr; 719 720 const DataLayout &DL = IC.getDataLayout(); 721 auto EltSize = DL.getTypeAllocSize(ET); 722 const auto Align = DL.getValueOrABITypeAlignment(LI.getAlign(), T); 723 724 auto *Addr = LI.getPointerOperand(); 725 auto *IdxType = Type::getInt64Ty(T->getContext()); 726 auto *Zero = ConstantInt::get(IdxType, 0); 727 728 Value *V = UndefValue::get(T); 729 uint64_t Offset = 0; 730 for (uint64_t i = 0; i < NumElements; i++) { 731 Value *Indices[2] = { 732 Zero, 733 ConstantInt::get(IdxType, i), 734 }; 735 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices), 736 Name + ".elt"); 737 auto *L = IC.Builder.CreateAlignedLoad(AT->getElementType(), Ptr, 738 commonAlignment(Align, Offset), 739 Name + ".unpack"); 740 AAMDNodes AAMD; 741 LI.getAAMetadata(AAMD); 742 L->setAAMetadata(AAMD); 743 V = IC.Builder.CreateInsertValue(V, L, i); 744 Offset += EltSize; 745 } 746 747 V->setName(Name); 748 return IC.replaceInstUsesWith(LI, V); 749 } 750 751 return nullptr; 752 } 753 754 // If we can determine that all possible objects pointed to by the provided 755 // pointer value are, not only dereferenceable, but also definitively less than 756 // or equal to the provided maximum size, then return true. Otherwise, return 757 // false (constant global values and allocas fall into this category). 758 // 759 // FIXME: This should probably live in ValueTracking (or similar). 760 static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize, 761 const DataLayout &DL) { 762 SmallPtrSet<Value *, 4> Visited; 763 SmallVector<Value *, 4> Worklist(1, V); 764 765 do { 766 Value *P = Worklist.pop_back_val(); 767 P = P->stripPointerCasts(); 768 769 if (!Visited.insert(P).second) 770 continue; 771 772 if (SelectInst *SI = dyn_cast<SelectInst>(P)) { 773 Worklist.push_back(SI->getTrueValue()); 774 Worklist.push_back(SI->getFalseValue()); 775 continue; 776 } 777 778 if (PHINode *PN = dyn_cast<PHINode>(P)) { 779 for (Value *IncValue : PN->incoming_values()) 780 Worklist.push_back(IncValue); 781 continue; 782 } 783 784 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) { 785 if (GA->isInterposable()) 786 return false; 787 Worklist.push_back(GA->getAliasee()); 788 continue; 789 } 790 791 // If we know how big this object is, and it is less than MaxSize, continue 792 // searching. Otherwise, return false. 793 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) { 794 if (!AI->getAllocatedType()->isSized()) 795 return false; 796 797 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize()); 798 if (!CS) 799 return false; 800 801 uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType()); 802 // Make sure that, even if the multiplication below would wrap as an 803 // uint64_t, we still do the right thing. 804 if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize)) 805 return false; 806 continue; 807 } 808 809 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) { 810 if (!GV->hasDefinitiveInitializer() || !GV->isConstant()) 811 return false; 812 813 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType()); 814 if (InitSize > MaxSize) 815 return false; 816 continue; 817 } 818 819 return false; 820 } while (!Worklist.empty()); 821 822 return true; 823 } 824 825 // If we're indexing into an object of a known size, and the outer index is 826 // not a constant, but having any value but zero would lead to undefined 827 // behavior, replace it with zero. 828 // 829 // For example, if we have: 830 // @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4 831 // ... 832 // %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x 833 // ... = load i32* %arrayidx, align 4 834 // Then we know that we can replace %x in the GEP with i64 0. 835 // 836 // FIXME: We could fold any GEP index to zero that would cause UB if it were 837 // not zero. Currently, we only handle the first such index. Also, we could 838 // also search through non-zero constant indices if we kept track of the 839 // offsets those indices implied. 840 static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI, 841 Instruction *MemI, unsigned &Idx) { 842 if (GEPI->getNumOperands() < 2) 843 return false; 844 845 // Find the first non-zero index of a GEP. If all indices are zero, return 846 // one past the last index. 847 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) { 848 unsigned I = 1; 849 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) { 850 Value *V = GEPI->getOperand(I); 851 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) 852 if (CI->isZero()) 853 continue; 854 855 break; 856 } 857 858 return I; 859 }; 860 861 // Skip through initial 'zero' indices, and find the corresponding pointer 862 // type. See if the next index is not a constant. 863 Idx = FirstNZIdx(GEPI); 864 if (Idx == GEPI->getNumOperands()) 865 return false; 866 if (isa<Constant>(GEPI->getOperand(Idx))) 867 return false; 868 869 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx); 870 Type *AllocTy = 871 GetElementPtrInst::getIndexedType(GEPI->getSourceElementType(), Ops); 872 if (!AllocTy || !AllocTy->isSized()) 873 return false; 874 const DataLayout &DL = IC.getDataLayout(); 875 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy); 876 877 // If there are more indices after the one we might replace with a zero, make 878 // sure they're all non-negative. If any of them are negative, the overall 879 // address being computed might be before the base address determined by the 880 // first non-zero index. 881 auto IsAllNonNegative = [&]() { 882 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) { 883 KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), 0, MemI); 884 if (Known.isNonNegative()) 885 continue; 886 return false; 887 } 888 889 return true; 890 }; 891 892 // FIXME: If the GEP is not inbounds, and there are extra indices after the 893 // one we'll replace, those could cause the address computation to wrap 894 // (rendering the IsAllNonNegative() check below insufficient). We can do 895 // better, ignoring zero indices (and other indices we can prove small 896 // enough not to wrap). 897 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds()) 898 return false; 899 900 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is 901 // also known to be dereferenceable. 902 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) && 903 IsAllNonNegative(); 904 } 905 906 // If we're indexing into an object with a variable index for the memory 907 // access, but the object has only one element, we can assume that the index 908 // will always be zero. If we replace the GEP, return it. 909 template <typename T> 910 static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr, 911 T &MemI) { 912 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) { 913 unsigned Idx; 914 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) { 915 Instruction *NewGEPI = GEPI->clone(); 916 NewGEPI->setOperand(Idx, 917 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0)); 918 NewGEPI->insertBefore(GEPI); 919 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI); 920 return NewGEPI; 921 } 922 } 923 924 return nullptr; 925 } 926 927 static bool canSimplifyNullStoreOrGEP(StoreInst &SI) { 928 if (NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace())) 929 return false; 930 931 auto *Ptr = SI.getPointerOperand(); 932 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) 933 Ptr = GEPI->getOperand(0); 934 return (isa<ConstantPointerNull>(Ptr) && 935 !NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace())); 936 } 937 938 static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) { 939 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) { 940 const Value *GEPI0 = GEPI->getOperand(0); 941 if (isa<ConstantPointerNull>(GEPI0) && 942 !NullPointerIsDefined(LI.getFunction(), GEPI->getPointerAddressSpace())) 943 return true; 944 } 945 if (isa<UndefValue>(Op) || 946 (isa<ConstantPointerNull>(Op) && 947 !NullPointerIsDefined(LI.getFunction(), LI.getPointerAddressSpace()))) 948 return true; 949 return false; 950 } 951 952 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) { 953 Value *Op = LI.getOperand(0); 954 955 // Try to canonicalize the loaded type. 956 if (Instruction *Res = combineLoadToOperationType(*this, LI)) 957 return Res; 958 959 // Attempt to improve the alignment. 960 unsigned KnownAlign = getOrEnforceKnownAlignment( 961 Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, &AC, &DT); 962 unsigned LoadAlign = LI.getAlignment(); 963 unsigned EffectiveLoadAlign = 964 LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType()); 965 966 if (KnownAlign > EffectiveLoadAlign) 967 LI.setAlignment(MaybeAlign(KnownAlign)); 968 else if (LoadAlign == 0) 969 LI.setAlignment(MaybeAlign(EffectiveLoadAlign)); 970 971 // Replace GEP indices if possible. 972 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) { 973 Worklist.push(NewGEPI); 974 return &LI; 975 } 976 977 if (Instruction *Res = unpackLoadToAggregate(*this, LI)) 978 return Res; 979 980 // Do really simple store-to-load forwarding and load CSE, to catch cases 981 // where there are several consecutive memory accesses to the same location, 982 // separated by a few arithmetic operations. 983 BasicBlock::iterator BBI(LI); 984 bool IsLoadCSE = false; 985 if (Value *AvailableVal = FindAvailableLoadedValue( 986 &LI, LI.getParent(), BBI, DefMaxInstsToScan, AA, &IsLoadCSE)) { 987 if (IsLoadCSE) 988 combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI, false); 989 990 return replaceInstUsesWith( 991 LI, Builder.CreateBitOrPointerCast(AvailableVal, LI.getType(), 992 LI.getName() + ".cast")); 993 } 994 995 // None of the following transforms are legal for volatile/ordered atomic 996 // loads. Most of them do apply for unordered atomics. 997 if (!LI.isUnordered()) return nullptr; 998 999 // load(gep null, ...) -> unreachable 1000 // load null/undef -> unreachable 1001 // TODO: Consider a target hook for valid address spaces for this xforms. 1002 if (canSimplifyNullLoadOrGEP(LI, Op)) { 1003 // Insert a new store to null instruction before the load to indicate 1004 // that this code is not reachable. We do this instead of inserting 1005 // an unreachable instruction directly because we cannot modify the 1006 // CFG. 1007 StoreInst *SI = new StoreInst(UndefValue::get(LI.getType()), 1008 Constant::getNullValue(Op->getType()), &LI); 1009 SI->setDebugLoc(LI.getDebugLoc()); 1010 return replaceInstUsesWith(LI, UndefValue::get(LI.getType())); 1011 } 1012 1013 if (Op->hasOneUse()) { 1014 // Change select and PHI nodes to select values instead of addresses: this 1015 // helps alias analysis out a lot, allows many others simplifications, and 1016 // exposes redundancy in the code. 1017 // 1018 // Note that we cannot do the transformation unless we know that the 1019 // introduced loads cannot trap! Something like this is valid as long as 1020 // the condition is always false: load (select bool %C, int* null, int* %G), 1021 // but it would not be valid if we transformed it to load from null 1022 // unconditionally. 1023 // 1024 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) { 1025 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2). 1026 const MaybeAlign Alignment(LI.getAlignment()); 1027 if (isSafeToLoadUnconditionally(SI->getOperand(1), LI.getType(), 1028 Alignment, DL, SI) && 1029 isSafeToLoadUnconditionally(SI->getOperand(2), LI.getType(), 1030 Alignment, DL, SI)) { 1031 LoadInst *V1 = 1032 Builder.CreateLoad(LI.getType(), SI->getOperand(1), 1033 SI->getOperand(1)->getName() + ".val"); 1034 LoadInst *V2 = 1035 Builder.CreateLoad(LI.getType(), SI->getOperand(2), 1036 SI->getOperand(2)->getName() + ".val"); 1037 assert(LI.isUnordered() && "implied by above"); 1038 V1->setAlignment(Alignment); 1039 V1->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); 1040 V2->setAlignment(Alignment); 1041 V2->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); 1042 return SelectInst::Create(SI->getCondition(), V1, V2); 1043 } 1044 1045 // load (select (cond, null, P)) -> load P 1046 if (isa<ConstantPointerNull>(SI->getOperand(1)) && 1047 !NullPointerIsDefined(SI->getFunction(), 1048 LI.getPointerAddressSpace())) 1049 return replaceOperand(LI, 0, SI->getOperand(2)); 1050 1051 // load (select (cond, P, null)) -> load P 1052 if (isa<ConstantPointerNull>(SI->getOperand(2)) && 1053 !NullPointerIsDefined(SI->getFunction(), 1054 LI.getPointerAddressSpace())) 1055 return replaceOperand(LI, 0, SI->getOperand(1)); 1056 } 1057 } 1058 return nullptr; 1059 } 1060 1061 /// Look for extractelement/insertvalue sequence that acts like a bitcast. 1062 /// 1063 /// \returns underlying value that was "cast", or nullptr otherwise. 1064 /// 1065 /// For example, if we have: 1066 /// 1067 /// %E0 = extractelement <2 x double> %U, i32 0 1068 /// %V0 = insertvalue [2 x double] undef, double %E0, 0 1069 /// %E1 = extractelement <2 x double> %U, i32 1 1070 /// %V1 = insertvalue [2 x double] %V0, double %E1, 1 1071 /// 1072 /// and the layout of a <2 x double> is isomorphic to a [2 x double], 1073 /// then %V1 can be safely approximated by a conceptual "bitcast" of %U. 1074 /// Note that %U may contain non-undef values where %V1 has undef. 1075 static Value *likeBitCastFromVector(InstCombiner &IC, Value *V) { 1076 Value *U = nullptr; 1077 while (auto *IV = dyn_cast<InsertValueInst>(V)) { 1078 auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand()); 1079 if (!E) 1080 return nullptr; 1081 auto *W = E->getVectorOperand(); 1082 if (!U) 1083 U = W; 1084 else if (U != W) 1085 return nullptr; 1086 auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand()); 1087 if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin()) 1088 return nullptr; 1089 V = IV->getAggregateOperand(); 1090 } 1091 if (!isa<UndefValue>(V) ||!U) 1092 return nullptr; 1093 1094 auto *UT = cast<VectorType>(U->getType()); 1095 auto *VT = V->getType(); 1096 // Check that types UT and VT are bitwise isomorphic. 1097 const auto &DL = IC.getDataLayout(); 1098 if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) { 1099 return nullptr; 1100 } 1101 if (auto *AT = dyn_cast<ArrayType>(VT)) { 1102 if (AT->getNumElements() != UT->getNumElements()) 1103 return nullptr; 1104 } else { 1105 auto *ST = cast<StructType>(VT); 1106 if (ST->getNumElements() != UT->getNumElements()) 1107 return nullptr; 1108 for (const auto *EltT : ST->elements()) { 1109 if (EltT != UT->getElementType()) 1110 return nullptr; 1111 } 1112 } 1113 return U; 1114 } 1115 1116 /// Combine stores to match the type of value being stored. 1117 /// 1118 /// The core idea here is that the memory does not have any intrinsic type and 1119 /// where we can we should match the type of a store to the type of value being 1120 /// stored. 1121 /// 1122 /// However, this routine must never change the width of a store or the number of 1123 /// stores as that would introduce a semantic change. This combine is expected to 1124 /// be a semantic no-op which just allows stores to more closely model the types 1125 /// of their incoming values. 1126 /// 1127 /// Currently, we also refuse to change the precise type used for an atomic or 1128 /// volatile store. This is debatable, and might be reasonable to change later. 1129 /// However, it is risky in case some backend or other part of LLVM is relying 1130 /// on the exact type stored to select appropriate atomic operations. 1131 /// 1132 /// \returns true if the store was successfully combined away. This indicates 1133 /// the caller must erase the store instruction. We have to let the caller erase 1134 /// the store instruction as otherwise there is no way to signal whether it was 1135 /// combined or not: IC.EraseInstFromFunction returns a null pointer. 1136 static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) { 1137 // FIXME: We could probably with some care handle both volatile and ordered 1138 // atomic stores here but it isn't clear that this is important. 1139 if (!SI.isUnordered()) 1140 return false; 1141 1142 // swifterror values can't be bitcasted. 1143 if (SI.getPointerOperand()->isSwiftError()) 1144 return false; 1145 1146 Value *V = SI.getValueOperand(); 1147 1148 // Fold away bit casts of the stored value by storing the original type. 1149 if (auto *BC = dyn_cast<BitCastInst>(V)) { 1150 V = BC->getOperand(0); 1151 if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) { 1152 combineStoreToNewValue(IC, SI, V); 1153 return true; 1154 } 1155 } 1156 1157 if (Value *U = likeBitCastFromVector(IC, V)) 1158 if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) { 1159 combineStoreToNewValue(IC, SI, U); 1160 return true; 1161 } 1162 1163 // FIXME: We should also canonicalize stores of vectors when their elements 1164 // are cast to other types. 1165 return false; 1166 } 1167 1168 static bool unpackStoreToAggregate(InstCombiner &IC, StoreInst &SI) { 1169 // FIXME: We could probably with some care handle both volatile and atomic 1170 // stores here but it isn't clear that this is important. 1171 if (!SI.isSimple()) 1172 return false; 1173 1174 Value *V = SI.getValueOperand(); 1175 Type *T = V->getType(); 1176 1177 if (!T->isAggregateType()) 1178 return false; 1179 1180 if (auto *ST = dyn_cast<StructType>(T)) { 1181 // If the struct only have one element, we unpack. 1182 unsigned Count = ST->getNumElements(); 1183 if (Count == 1) { 1184 V = IC.Builder.CreateExtractValue(V, 0); 1185 combineStoreToNewValue(IC, SI, V); 1186 return true; 1187 } 1188 1189 // We don't want to break loads with padding here as we'd loose 1190 // the knowledge that padding exists for the rest of the pipeline. 1191 const DataLayout &DL = IC.getDataLayout(); 1192 auto *SL = DL.getStructLayout(ST); 1193 if (SL->hasPadding()) 1194 return false; 1195 1196 const auto Align = DL.getValueOrABITypeAlignment(SI.getAlign(), ST); 1197 1198 SmallString<16> EltName = V->getName(); 1199 EltName += ".elt"; 1200 auto *Addr = SI.getPointerOperand(); 1201 SmallString<16> AddrName = Addr->getName(); 1202 AddrName += ".repack"; 1203 1204 auto *IdxType = Type::getInt32Ty(ST->getContext()); 1205 auto *Zero = ConstantInt::get(IdxType, 0); 1206 for (unsigned i = 0; i < Count; i++) { 1207 Value *Indices[2] = { 1208 Zero, 1209 ConstantInt::get(IdxType, i), 1210 }; 1211 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices), 1212 AddrName); 1213 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName); 1214 auto EltAlign = commonAlignment(Align, SL->getElementOffset(i)); 1215 llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign); 1216 AAMDNodes AAMD; 1217 SI.getAAMetadata(AAMD); 1218 NS->setAAMetadata(AAMD); 1219 } 1220 1221 return true; 1222 } 1223 1224 if (auto *AT = dyn_cast<ArrayType>(T)) { 1225 // If the array only have one element, we unpack. 1226 auto NumElements = AT->getNumElements(); 1227 if (NumElements == 1) { 1228 V = IC.Builder.CreateExtractValue(V, 0); 1229 combineStoreToNewValue(IC, SI, V); 1230 return true; 1231 } 1232 1233 // Bail out if the array is too large. Ideally we would like to optimize 1234 // arrays of arbitrary size but this has a terrible impact on compile time. 1235 // The threshold here is chosen arbitrarily, maybe needs a little bit of 1236 // tuning. 1237 if (NumElements > IC.MaxArraySizeForCombine) 1238 return false; 1239 1240 const DataLayout &DL = IC.getDataLayout(); 1241 auto EltSize = DL.getTypeAllocSize(AT->getElementType()); 1242 const auto Align = DL.getValueOrABITypeAlignment(SI.getAlign(), T); 1243 1244 SmallString<16> EltName = V->getName(); 1245 EltName += ".elt"; 1246 auto *Addr = SI.getPointerOperand(); 1247 SmallString<16> AddrName = Addr->getName(); 1248 AddrName += ".repack"; 1249 1250 auto *IdxType = Type::getInt64Ty(T->getContext()); 1251 auto *Zero = ConstantInt::get(IdxType, 0); 1252 1253 uint64_t Offset = 0; 1254 for (uint64_t i = 0; i < NumElements; i++) { 1255 Value *Indices[2] = { 1256 Zero, 1257 ConstantInt::get(IdxType, i), 1258 }; 1259 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices), 1260 AddrName); 1261 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName); 1262 auto EltAlign = commonAlignment(Align, Offset); 1263 Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign); 1264 AAMDNodes AAMD; 1265 SI.getAAMetadata(AAMD); 1266 NS->setAAMetadata(AAMD); 1267 Offset += EltSize; 1268 } 1269 1270 return true; 1271 } 1272 1273 return false; 1274 } 1275 1276 /// equivalentAddressValues - Test if A and B will obviously have the same 1277 /// value. This includes recognizing that %t0 and %t1 will have the same 1278 /// value in code like this: 1279 /// %t0 = getelementptr \@a, 0, 3 1280 /// store i32 0, i32* %t0 1281 /// %t1 = getelementptr \@a, 0, 3 1282 /// %t2 = load i32* %t1 1283 /// 1284 static bool equivalentAddressValues(Value *A, Value *B) { 1285 // Test if the values are trivially equivalent. 1286 if (A == B) return true; 1287 1288 // Test if the values come form identical arithmetic instructions. 1289 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because 1290 // its only used to compare two uses within the same basic block, which 1291 // means that they'll always either have the same value or one of them 1292 // will have an undefined value. 1293 if (isa<BinaryOperator>(A) || 1294 isa<CastInst>(A) || 1295 isa<PHINode>(A) || 1296 isa<GetElementPtrInst>(A)) 1297 if (Instruction *BI = dyn_cast<Instruction>(B)) 1298 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI)) 1299 return true; 1300 1301 // Otherwise they may not be equivalent. 1302 return false; 1303 } 1304 1305 /// Converts store (bitcast (load (bitcast (select ...)))) to 1306 /// store (load (select ...)), where select is minmax: 1307 /// select ((cmp load V1, load V2), V1, V2). 1308 static bool removeBitcastsFromLoadStoreOnMinMax(InstCombiner &IC, 1309 StoreInst &SI) { 1310 // bitcast? 1311 if (!match(SI.getPointerOperand(), m_BitCast(m_Value()))) 1312 return false; 1313 // load? integer? 1314 Value *LoadAddr; 1315 if (!match(SI.getValueOperand(), m_Load(m_BitCast(m_Value(LoadAddr))))) 1316 return false; 1317 auto *LI = cast<LoadInst>(SI.getValueOperand()); 1318 if (!LI->getType()->isIntegerTy()) 1319 return false; 1320 Type *CmpLoadTy; 1321 if (!isMinMaxWithLoads(LoadAddr, CmpLoadTy)) 1322 return false; 1323 1324 // Make sure the type would actually change. 1325 // This condition can be hit with chains of bitcasts. 1326 if (LI->getType() == CmpLoadTy) 1327 return false; 1328 1329 // Make sure we're not changing the size of the load/store. 1330 const auto &DL = IC.getDataLayout(); 1331 if (DL.getTypeStoreSizeInBits(LI->getType()) != 1332 DL.getTypeStoreSizeInBits(CmpLoadTy)) 1333 return false; 1334 1335 if (!all_of(LI->users(), [LI, LoadAddr](User *U) { 1336 auto *SI = dyn_cast<StoreInst>(U); 1337 return SI && SI->getPointerOperand() != LI && 1338 peekThroughBitcast(SI->getPointerOperand()) != LoadAddr && 1339 !SI->getPointerOperand()->isSwiftError(); 1340 })) 1341 return false; 1342 1343 IC.Builder.SetInsertPoint(LI); 1344 LoadInst *NewLI = IC.combineLoadToNewType(*LI, CmpLoadTy); 1345 // Replace all the stores with stores of the newly loaded value. 1346 for (auto *UI : LI->users()) { 1347 auto *USI = cast<StoreInst>(UI); 1348 IC.Builder.SetInsertPoint(USI); 1349 combineStoreToNewValue(IC, *USI, NewLI); 1350 } 1351 IC.replaceInstUsesWith(*LI, UndefValue::get(LI->getType())); 1352 IC.eraseInstFromFunction(*LI); 1353 return true; 1354 } 1355 1356 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) { 1357 Value *Val = SI.getOperand(0); 1358 Value *Ptr = SI.getOperand(1); 1359 1360 // Try to canonicalize the stored type. 1361 if (combineStoreToValueType(*this, SI)) 1362 return eraseInstFromFunction(SI); 1363 1364 // Attempt to improve the alignment. 1365 const Align KnownAlign = Align(getOrEnforceKnownAlignment( 1366 Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, &AC, &DT)); 1367 const MaybeAlign StoreAlign = MaybeAlign(SI.getAlignment()); 1368 const Align EffectiveStoreAlign = 1369 StoreAlign ? *StoreAlign : Align(DL.getABITypeAlignment(Val->getType())); 1370 1371 if (KnownAlign > EffectiveStoreAlign) 1372 SI.setAlignment(KnownAlign); 1373 else if (!StoreAlign) 1374 SI.setAlignment(EffectiveStoreAlign); 1375 1376 // Try to canonicalize the stored type. 1377 if (unpackStoreToAggregate(*this, SI)) 1378 return eraseInstFromFunction(SI); 1379 1380 if (removeBitcastsFromLoadStoreOnMinMax(*this, SI)) 1381 return eraseInstFromFunction(SI); 1382 1383 // Replace GEP indices if possible. 1384 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) { 1385 Worklist.push(NewGEPI); 1386 return &SI; 1387 } 1388 1389 // Don't hack volatile/ordered stores. 1390 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring. 1391 if (!SI.isUnordered()) return nullptr; 1392 1393 // If the RHS is an alloca with a single use, zapify the store, making the 1394 // alloca dead. 1395 if (Ptr->hasOneUse()) { 1396 if (isa<AllocaInst>(Ptr)) 1397 return eraseInstFromFunction(SI); 1398 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) { 1399 if (isa<AllocaInst>(GEP->getOperand(0))) { 1400 if (GEP->getOperand(0)->hasOneUse()) 1401 return eraseInstFromFunction(SI); 1402 } 1403 } 1404 } 1405 1406 // If we have a store to a location which is known constant, we can conclude 1407 // that the store must be storing the constant value (else the memory 1408 // wouldn't be constant), and this must be a noop. 1409 if (AA->pointsToConstantMemory(Ptr)) 1410 return eraseInstFromFunction(SI); 1411 1412 // Do really simple DSE, to catch cases where there are several consecutive 1413 // stores to the same location, separated by a few arithmetic operations. This 1414 // situation often occurs with bitfield accesses. 1415 BasicBlock::iterator BBI(SI); 1416 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts; 1417 --ScanInsts) { 1418 --BBI; 1419 // Don't count debug info directives, lest they affect codegen, 1420 // and we skip pointer-to-pointer bitcasts, which are NOPs. 1421 if (isa<DbgInfoIntrinsic>(BBI) || 1422 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) { 1423 ScanInsts++; 1424 continue; 1425 } 1426 1427 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) { 1428 // Prev store isn't volatile, and stores to the same location? 1429 if (PrevSI->isUnordered() && equivalentAddressValues(PrevSI->getOperand(1), 1430 SI.getOperand(1))) { 1431 ++NumDeadStore; 1432 // Manually add back the original store to the worklist now, so it will 1433 // be processed after the operands of the removed store, as this may 1434 // expose additional DSE opportunities. 1435 Worklist.push(&SI); 1436 eraseInstFromFunction(*PrevSI); 1437 return nullptr; 1438 } 1439 break; 1440 } 1441 1442 // If this is a load, we have to stop. However, if the loaded value is from 1443 // the pointer we're loading and is producing the pointer we're storing, 1444 // then *this* store is dead (X = load P; store X -> P). 1445 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) { 1446 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) { 1447 assert(SI.isUnordered() && "can't eliminate ordering operation"); 1448 return eraseInstFromFunction(SI); 1449 } 1450 1451 // Otherwise, this is a load from some other location. Stores before it 1452 // may not be dead. 1453 break; 1454 } 1455 1456 // Don't skip over loads, throws or things that can modify memory. 1457 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow()) 1458 break; 1459 } 1460 1461 // store X, null -> turns into 'unreachable' in SimplifyCFG 1462 // store X, GEP(null, Y) -> turns into 'unreachable' in SimplifyCFG 1463 if (canSimplifyNullStoreOrGEP(SI)) { 1464 if (!isa<UndefValue>(Val)) 1465 return replaceOperand(SI, 0, UndefValue::get(Val->getType())); 1466 return nullptr; // Do not modify these! 1467 } 1468 1469 // store undef, Ptr -> noop 1470 if (isa<UndefValue>(Val)) 1471 return eraseInstFromFunction(SI); 1472 1473 // If this store is the second-to-last instruction in the basic block 1474 // (excluding debug info and bitcasts of pointers) and if the block ends with 1475 // an unconditional branch, try to move the store to the successor block. 1476 BBI = SI.getIterator(); 1477 do { 1478 ++BBI; 1479 } while (isa<DbgInfoIntrinsic>(BBI) || 1480 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())); 1481 1482 if (BranchInst *BI = dyn_cast<BranchInst>(BBI)) 1483 if (BI->isUnconditional()) 1484 mergeStoreIntoSuccessor(SI); 1485 1486 return nullptr; 1487 } 1488 1489 /// Try to transform: 1490 /// if () { *P = v1; } else { *P = v2 } 1491 /// or: 1492 /// *P = v1; if () { *P = v2; } 1493 /// into a phi node with a store in the successor. 1494 bool InstCombiner::mergeStoreIntoSuccessor(StoreInst &SI) { 1495 assert(SI.isUnordered() && 1496 "This code has not been audited for volatile or ordered store case."); 1497 1498 // Check if the successor block has exactly 2 incoming edges. 1499 BasicBlock *StoreBB = SI.getParent(); 1500 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0); 1501 if (!DestBB->hasNPredecessors(2)) 1502 return false; 1503 1504 // Capture the other block (the block that doesn't contain our store). 1505 pred_iterator PredIter = pred_begin(DestBB); 1506 if (*PredIter == StoreBB) 1507 ++PredIter; 1508 BasicBlock *OtherBB = *PredIter; 1509 1510 // Bail out if all of the relevant blocks aren't distinct. This can happen, 1511 // for example, if SI is in an infinite loop. 1512 if (StoreBB == DestBB || OtherBB == DestBB) 1513 return false; 1514 1515 // Verify that the other block ends in a branch and is not otherwise empty. 1516 BasicBlock::iterator BBI(OtherBB->getTerminator()); 1517 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI); 1518 if (!OtherBr || BBI == OtherBB->begin()) 1519 return false; 1520 1521 // If the other block ends in an unconditional branch, check for the 'if then 1522 // else' case. There is an instruction before the branch. 1523 StoreInst *OtherStore = nullptr; 1524 if (OtherBr->isUnconditional()) { 1525 --BBI; 1526 // Skip over debugging info. 1527 while (isa<DbgInfoIntrinsic>(BBI) || 1528 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) { 1529 if (BBI==OtherBB->begin()) 1530 return false; 1531 --BBI; 1532 } 1533 // If this isn't a store, isn't a store to the same location, or is not the 1534 // right kind of store, bail out. 1535 OtherStore = dyn_cast<StoreInst>(BBI); 1536 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) || 1537 !SI.isSameOperationAs(OtherStore)) 1538 return false; 1539 } else { 1540 // Otherwise, the other block ended with a conditional branch. If one of the 1541 // destinations is StoreBB, then we have the if/then case. 1542 if (OtherBr->getSuccessor(0) != StoreBB && 1543 OtherBr->getSuccessor(1) != StoreBB) 1544 return false; 1545 1546 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an 1547 // if/then triangle. See if there is a store to the same ptr as SI that 1548 // lives in OtherBB. 1549 for (;; --BBI) { 1550 // Check to see if we find the matching store. 1551 if ((OtherStore = dyn_cast<StoreInst>(BBI))) { 1552 if (OtherStore->getOperand(1) != SI.getOperand(1) || 1553 !SI.isSameOperationAs(OtherStore)) 1554 return false; 1555 break; 1556 } 1557 // If we find something that may be using or overwriting the stored 1558 // value, or if we run out of instructions, we can't do the transform. 1559 if (BBI->mayReadFromMemory() || BBI->mayThrow() || 1560 BBI->mayWriteToMemory() || BBI == OtherBB->begin()) 1561 return false; 1562 } 1563 1564 // In order to eliminate the store in OtherBr, we have to make sure nothing 1565 // reads or overwrites the stored value in StoreBB. 1566 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) { 1567 // FIXME: This should really be AA driven. 1568 if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory()) 1569 return false; 1570 } 1571 } 1572 1573 // Insert a PHI node now if we need it. 1574 Value *MergedVal = OtherStore->getOperand(0); 1575 // The debug locations of the original instructions might differ. Merge them. 1576 DebugLoc MergedLoc = DILocation::getMergedLocation(SI.getDebugLoc(), 1577 OtherStore->getDebugLoc()); 1578 if (MergedVal != SI.getOperand(0)) { 1579 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge"); 1580 PN->addIncoming(SI.getOperand(0), SI.getParent()); 1581 PN->addIncoming(OtherStore->getOperand(0), OtherBB); 1582 MergedVal = InsertNewInstBefore(PN, DestBB->front()); 1583 PN->setDebugLoc(MergedLoc); 1584 } 1585 1586 // Advance to a place where it is safe to insert the new store and insert it. 1587 BBI = DestBB->getFirstInsertionPt(); 1588 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1), SI.isVolatile(), 1589 MaybeAlign(SI.getAlignment()), 1590 SI.getOrdering(), SI.getSyncScopeID()); 1591 InsertNewInstBefore(NewSI, *BBI); 1592 NewSI->setDebugLoc(MergedLoc); 1593 1594 // If the two stores had AA tags, merge them. 1595 AAMDNodes AATags; 1596 SI.getAAMetadata(AATags); 1597 if (AATags) { 1598 OtherStore->getAAMetadata(AATags, /* Merge = */ true); 1599 NewSI->setAAMetadata(AATags); 1600 } 1601 1602 // Nuke the old stores. 1603 eraseInstFromFunction(SI); 1604 eraseInstFromFunction(*OtherStore); 1605 return true; 1606 } 1607