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