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