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