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