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