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