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