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