[PM] Split the AssumptionTracker immutable pass into two separate APIs:
[oota-llvm.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 "InstCombine.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/Loads.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 using namespace llvm;
23
24 #define DEBUG_TYPE "instcombine"
25
26 STATISTIC(NumDeadStore,    "Number of dead stores eliminated");
27 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
28
29 /// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
30 /// some part of a constant global variable.  This intentionally only accepts
31 /// constant expressions because we can't rewrite arbitrary instructions.
32 static bool pointsToConstantGlobal(Value *V) {
33   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
34     return GV->isConstant();
35
36   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
37     if (CE->getOpcode() == Instruction::BitCast ||
38         CE->getOpcode() == Instruction::AddrSpaceCast ||
39         CE->getOpcode() == Instruction::GetElementPtr)
40       return pointsToConstantGlobal(CE->getOperand(0));
41   }
42   return false;
43 }
44
45 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
46 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
47 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
48 /// track of whether it moves the pointer (with IsOffset) but otherwise traverse
49 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
50 /// the alloca, and if the source pointer is a pointer to a constant global, we
51 /// can optimize this.
52 static bool
53 isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
54                                SmallVectorImpl<Instruction *> &ToDelete) {
55   // We track lifetime intrinsics as we encounter them.  If we decide to go
56   // ahead and replace the value with the global, this lets the caller quickly
57   // eliminate the markers.
58
59   SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
60   ValuesToInspect.push_back(std::make_pair(V, false));
61   while (!ValuesToInspect.empty()) {
62     auto ValuePair = ValuesToInspect.pop_back_val();
63     const bool IsOffset = ValuePair.second;
64     for (auto &U : ValuePair.first->uses()) {
65       Instruction *I = cast<Instruction>(U.getUser());
66
67       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
68         // Ignore non-volatile loads, they are always ok.
69         if (!LI->isSimple()) return false;
70         continue;
71       }
72
73       if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
74         // If uses of the bitcast are ok, we are ok.
75         ValuesToInspect.push_back(std::make_pair(I, IsOffset));
76         continue;
77       }
78       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
79         // If the GEP has all zero indices, it doesn't offset the pointer. If it
80         // doesn't, it does.
81         ValuesToInspect.push_back(
82             std::make_pair(I, IsOffset || !GEP->hasAllZeroIndices()));
83         continue;
84       }
85
86       if (CallSite CS = I) {
87         // If this is the function being called then we treat it like a load and
88         // ignore it.
89         if (CS.isCallee(&U))
90           continue;
91
92         // Inalloca arguments are clobbered by the call.
93         unsigned ArgNo = CS.getArgumentNo(&U);
94         if (CS.isInAllocaArgument(ArgNo))
95           return false;
96
97         // If this is a readonly/readnone call site, then we know it is just a
98         // load (but one that potentially returns the value itself), so we can
99         // ignore it if we know that the value isn't captured.
100         if (CS.onlyReadsMemory() &&
101             (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
102           continue;
103
104         // If this is being passed as a byval argument, the caller is making a
105         // copy, so it is only a read of the alloca.
106         if (CS.isByValArgument(ArgNo))
107           continue;
108       }
109
110       // Lifetime intrinsics can be handled by the caller.
111       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
112         if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
113             II->getIntrinsicID() == Intrinsic::lifetime_end) {
114           assert(II->use_empty() && "Lifetime markers have no result to use!");
115           ToDelete.push_back(II);
116           continue;
117         }
118       }
119
120       // If this is isn't our memcpy/memmove, reject it as something we can't
121       // handle.
122       MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
123       if (!MI)
124         return false;
125
126       // If the transfer is using the alloca as a source of the transfer, then
127       // ignore it since it is a load (unless the transfer is volatile).
128       if (U.getOperandNo() == 1) {
129         if (MI->isVolatile()) return false;
130         continue;
131       }
132
133       // If we already have seen a copy, reject the second one.
134       if (TheCopy) return false;
135
136       // If the pointer has been offset from the start of the alloca, we can't
137       // safely handle this.
138       if (IsOffset) return false;
139
140       // If the memintrinsic isn't using the alloca as the dest, reject it.
141       if (U.getOperandNo() != 0) return false;
142
143       // If the source of the memcpy/move is not a constant global, reject it.
144       if (!pointsToConstantGlobal(MI->getSource()))
145         return false;
146
147       // Otherwise, the transform is safe.  Remember the copy instruction.
148       TheCopy = MI;
149     }
150   }
151   return true;
152 }
153
154 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
155 /// modified by a copy from a constant global.  If we can prove this, we can
156 /// replace any uses of the alloca with uses of the global directly.
157 static MemTransferInst *
158 isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
159                                SmallVectorImpl<Instruction *> &ToDelete) {
160   MemTransferInst *TheCopy = nullptr;
161   if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
162     return TheCopy;
163   return nullptr;
164 }
165
166 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
167   // Ensure that the alloca array size argument has type intptr_t, so that
168   // any casting is exposed early.
169   if (DL) {
170     Type *IntPtrTy = DL->getIntPtrType(AI.getType());
171     if (AI.getArraySize()->getType() != IntPtrTy) {
172       Value *V = Builder->CreateIntCast(AI.getArraySize(),
173                                         IntPtrTy, false);
174       AI.setOperand(0, V);
175       return &AI;
176     }
177   }
178
179   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
180   if (AI.isArrayAllocation()) {  // Check C != 1
181     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
182       Type *NewTy =
183         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
184       AllocaInst *New = Builder->CreateAlloca(NewTy, nullptr, AI.getName());
185       New->setAlignment(AI.getAlignment());
186
187       // Scan to the end of the allocation instructions, to skip over a block of
188       // allocas if possible...also skip interleaved debug info
189       //
190       BasicBlock::iterator It = New;
191       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
192
193       // Now that I is pointing to the first non-allocation-inst in the block,
194       // insert our getelementptr instruction...
195       //
196       Type *IdxTy = DL
197                   ? DL->getIntPtrType(AI.getType())
198                   : Type::getInt64Ty(AI.getContext());
199       Value *NullIdx = Constant::getNullValue(IdxTy);
200       Value *Idx[2] = { NullIdx, NullIdx };
201       Instruction *GEP =
202         GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
203       InsertNewInstBefore(GEP, *It);
204
205       // Now make everything use the getelementptr instead of the original
206       // allocation.
207       return ReplaceInstUsesWith(AI, GEP);
208     } else if (isa<UndefValue>(AI.getArraySize())) {
209       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
210     }
211   }
212
213   if (DL && AI.getAllocatedType()->isSized()) {
214     // If the alignment is 0 (unspecified), assign it the preferred alignment.
215     if (AI.getAlignment() == 0)
216       AI.setAlignment(DL->getPrefTypeAlignment(AI.getAllocatedType()));
217
218     // Move all alloca's of zero byte objects to the entry block and merge them
219     // together.  Note that we only do this for alloca's, because malloc should
220     // allocate and return a unique pointer, even for a zero byte allocation.
221     if (DL->getTypeAllocSize(AI.getAllocatedType()) == 0) {
222       // For a zero sized alloca there is no point in doing an array allocation.
223       // This is helpful if the array size is a complicated expression not used
224       // elsewhere.
225       if (AI.isArrayAllocation()) {
226         AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
227         return &AI;
228       }
229
230       // Get the first instruction in the entry block.
231       BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
232       Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
233       if (FirstInst != &AI) {
234         // If the entry block doesn't start with a zero-size alloca then move
235         // this one to the start of the entry block.  There is no problem with
236         // dominance as the array size was forced to a constant earlier already.
237         AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
238         if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
239             DL->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
240           AI.moveBefore(FirstInst);
241           return &AI;
242         }
243
244         // If the alignment of the entry block alloca is 0 (unspecified),
245         // assign it the preferred alignment.
246         if (EntryAI->getAlignment() == 0)
247           EntryAI->setAlignment(
248             DL->getPrefTypeAlignment(EntryAI->getAllocatedType()));
249         // Replace this zero-sized alloca with the one at the start of the entry
250         // block after ensuring that the address will be aligned enough for both
251         // types.
252         unsigned MaxAlign = std::max(EntryAI->getAlignment(),
253                                      AI.getAlignment());
254         EntryAI->setAlignment(MaxAlign);
255         if (AI.getType() != EntryAI->getType())
256           return new BitCastInst(EntryAI, AI.getType());
257         return ReplaceInstUsesWith(AI, EntryAI);
258       }
259     }
260   }
261
262   if (AI.getAlignment()) {
263     // Check to see if this allocation is only modified by a memcpy/memmove from
264     // a constant global whose alignment is equal to or exceeds that of the
265     // allocation.  If this is the case, we can change all users to use
266     // the constant global instead.  This is commonly produced by the CFE by
267     // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
268     // is only subsequently read.
269     SmallVector<Instruction *, 4> ToDelete;
270     if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
271       unsigned SourceAlign = getOrEnforceKnownAlignment(
272           Copy->getSource(), AI.getAlignment(), DL, AC, &AI, DT);
273       if (AI.getAlignment() <= SourceAlign) {
274         DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
275         DEBUG(dbgs() << "  memcpy = " << *Copy << '\n');
276         for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
277           EraseInstFromFunction(*ToDelete[i]);
278         Constant *TheSrc = cast<Constant>(Copy->getSource());
279         Constant *Cast
280           = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
281         Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
282         EraseInstFromFunction(*Copy);
283         ++NumGlobalCopies;
284         return NewI;
285       }
286     }
287   }
288
289   // At last, use the generic allocation site handler to aggressively remove
290   // unused allocas.
291   return visitAllocSite(AI);
292 }
293
294 /// \brief Helper to combine a load to a new type.
295 ///
296 /// This just does the work of combining a load to a new type. It handles
297 /// metadata, etc., and returns the new instruction. The \c NewTy should be the
298 /// loaded *value* type. This will convert it to a pointer, cast the operand to
299 /// that pointer type, load it, etc.
300 ///
301 /// Note that this will create all of the instructions with whatever insert
302 /// point the \c InstCombiner currently is using.
303 static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy) {
304   Value *Ptr = LI.getPointerOperand();
305   unsigned AS = LI.getPointerAddressSpace();
306   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
307   LI.getAllMetadata(MD);
308
309   LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
310       IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
311       LI.getAlignment(), LI.getName());
312   for (const auto &MDPair : MD) {
313     unsigned ID = MDPair.first;
314     MDNode *N = MDPair.second;
315     // Note, essentially every kind of metadata should be preserved here! This
316     // routine is supposed to clone a load instruction changing *only its type*.
317     // The only metadata it makes sense to drop is metadata which is invalidated
318     // when the pointer type changes. This should essentially never be the case
319     // in LLVM, but we explicitly switch over only known metadata to be
320     // conservatively correct. If you are adding metadata to LLVM which pertains
321     // to loads, you almost certainly want to add it here.
322     switch (ID) {
323     case LLVMContext::MD_dbg:
324     case LLVMContext::MD_tbaa:
325     case LLVMContext::MD_prof:
326     case LLVMContext::MD_fpmath:
327     case LLVMContext::MD_tbaa_struct:
328     case LLVMContext::MD_invariant_load:
329     case LLVMContext::MD_alias_scope:
330     case LLVMContext::MD_noalias:
331     case LLVMContext::MD_nontemporal:
332     case LLVMContext::MD_mem_parallel_loop_access:
333     case LLVMContext::MD_nonnull:
334       // All of these directly apply.
335       NewLoad->setMetadata(ID, N);
336       break;
337
338     case LLVMContext::MD_range:
339       // FIXME: It would be nice to propagate this in some way, but the type
340       // conversions make it hard.
341       break;
342     }
343   }
344   return NewLoad;
345 }
346
347 /// \brief Combine loads to match the type of value their uses after looking
348 /// through intervening bitcasts.
349 ///
350 /// The core idea here is that if the result of a load is used in an operation,
351 /// we should load the type most conducive to that operation. For example, when
352 /// loading an integer and converting that immediately to a pointer, we should
353 /// instead directly load a pointer.
354 ///
355 /// However, this routine must never change the width of a load or the number of
356 /// loads as that would introduce a semantic change. This combine is expected to
357 /// be a semantic no-op which just allows loads to more closely model the types
358 /// of their consuming operations.
359 ///
360 /// Currently, we also refuse to change the precise type used for an atomic load
361 /// or a volatile load. This is debatable, and might be reasonable to change
362 /// later. However, it is risky in case some backend or other part of LLVM is
363 /// relying on the exact type loaded to select appropriate atomic operations.
364 static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
365   // FIXME: We could probably with some care handle both volatile and atomic
366   // loads here but it isn't clear that this is important.
367   if (!LI.isSimple())
368     return nullptr;
369
370   if (LI.use_empty())
371     return nullptr;
372
373
374   // Fold away bit casts of the loaded value by loading the desired type.
375   if (LI.hasOneUse())
376     if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) {
377       LoadInst *NewLoad = combineLoadToNewType(IC, LI, BC->getDestTy());
378       BC->replaceAllUsesWith(NewLoad);
379       IC.EraseInstFromFunction(*BC);
380       return &LI;
381     }
382
383   // FIXME: We should also canonicalize loads of vectors when their elements are
384   // cast to other types.
385   return nullptr;
386 }
387
388 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
389   Value *Op = LI.getOperand(0);
390
391   // Try to canonicalize the loaded type.
392   if (Instruction *Res = combineLoadToOperationType(*this, LI))
393     return Res;
394
395   // Attempt to improve the alignment.
396   if (DL) {
397     unsigned KnownAlign = getOrEnforceKnownAlignment(
398         Op, DL->getPrefTypeAlignment(LI.getType()), DL, AC, &LI, DT);
399     unsigned LoadAlign = LI.getAlignment();
400     unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
401       DL->getABITypeAlignment(LI.getType());
402
403     if (KnownAlign > EffectiveLoadAlign)
404       LI.setAlignment(KnownAlign);
405     else if (LoadAlign == 0)
406       LI.setAlignment(EffectiveLoadAlign);
407   }
408
409   // None of the following transforms are legal for volatile/atomic loads.
410   // FIXME: Some of it is okay for atomic loads; needs refactoring.
411   if (!LI.isSimple()) return nullptr;
412
413   // Do really simple store-to-load forwarding and load CSE, to catch cases
414   // where there are several consecutive memory accesses to the same location,
415   // separated by a few arithmetic operations.
416   BasicBlock::iterator BBI = &LI;
417   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
418     return ReplaceInstUsesWith(
419         LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
420                                             LI.getName() + ".cast"));
421
422   // load(gep null, ...) -> unreachable
423   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
424     const Value *GEPI0 = GEPI->getOperand(0);
425     // TODO: Consider a target hook for valid address spaces for this xform.
426     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
427       // Insert a new store to null instruction before the load to indicate
428       // that this code is not reachable.  We do this instead of inserting
429       // an unreachable instruction directly because we cannot modify the
430       // CFG.
431       new StoreInst(UndefValue::get(LI.getType()),
432                     Constant::getNullValue(Op->getType()), &LI);
433       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
434     }
435   }
436
437   // load null/undef -> unreachable
438   // TODO: Consider a target hook for valid address spaces for this xform.
439   if (isa<UndefValue>(Op) ||
440       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
441     // Insert a new store to null instruction before the load to indicate that
442     // this code is not reachable.  We do this instead of inserting an
443     // unreachable instruction directly because we cannot modify the CFG.
444     new StoreInst(UndefValue::get(LI.getType()),
445                   Constant::getNullValue(Op->getType()), &LI);
446     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
447   }
448
449   if (Op->hasOneUse()) {
450     // Change select and PHI nodes to select values instead of addresses: this
451     // helps alias analysis out a lot, allows many others simplifications, and
452     // exposes redundancy in the code.
453     //
454     // Note that we cannot do the transformation unless we know that the
455     // introduced loads cannot trap!  Something like this is valid as long as
456     // the condition is always false: load (select bool %C, int* null, int* %G),
457     // but it would not be valid if we transformed it to load from null
458     // unconditionally.
459     //
460     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
461       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
462       unsigned Align = LI.getAlignment();
463       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
464           isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
465         LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
466                                            SI->getOperand(1)->getName()+".val");
467         LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
468                                            SI->getOperand(2)->getName()+".val");
469         V1->setAlignment(Align);
470         V2->setAlignment(Align);
471         return SelectInst::Create(SI->getCondition(), V1, V2);
472       }
473
474       // load (select (cond, null, P)) -> load P
475       if (isa<ConstantPointerNull>(SI->getOperand(1)) && 
476           LI.getPointerAddressSpace() == 0) {
477         LI.setOperand(0, SI->getOperand(2));
478         return &LI;
479       }
480
481       // load (select (cond, P, null)) -> load P
482       if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
483           LI.getPointerAddressSpace() == 0) {
484         LI.setOperand(0, SI->getOperand(1));
485         return &LI;
486       }
487     }
488   }
489   return nullptr;
490 }
491
492 /// \brief Combine stores to match the type of value being stored.
493 ///
494 /// The core idea here is that the memory does not have any intrinsic type and
495 /// where we can we should match the type of a store to the type of value being
496 /// stored.
497 ///
498 /// However, this routine must never change the width of a store or the number of
499 /// stores as that would introduce a semantic change. This combine is expected to
500 /// be a semantic no-op which just allows stores to more closely model the types
501 /// of their incoming values.
502 ///
503 /// Currently, we also refuse to change the precise type used for an atomic or
504 /// volatile store. This is debatable, and might be reasonable to change later.
505 /// However, it is risky in case some backend or other part of LLVM is relying
506 /// on the exact type stored to select appropriate atomic operations.
507 ///
508 /// \returns true if the store was successfully combined away. This indicates
509 /// the caller must erase the store instruction. We have to let the caller erase
510 /// the store instruction sas otherwise there is no way to signal whether it was
511 /// combined or not: IC.EraseInstFromFunction returns a null pointer.
512 static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
513   // FIXME: We could probably with some care handle both volatile and atomic
514   // stores here but it isn't clear that this is important.
515   if (!SI.isSimple())
516     return false;
517
518   Value *Ptr = SI.getPointerOperand();
519   Value *V = SI.getValueOperand();
520   unsigned AS = SI.getPointerAddressSpace();
521   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
522   SI.getAllMetadata(MD);
523
524   // Fold away bit casts of the stored value by storing the original type.
525   if (auto *BC = dyn_cast<BitCastInst>(V)) {
526     V = BC->getOperand(0);
527     StoreInst *NewStore = IC.Builder->CreateAlignedStore(
528         V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
529         SI.getAlignment());
530     for (const auto &MDPair : MD) {
531       unsigned ID = MDPair.first;
532       MDNode *N = MDPair.second;
533       // Note, essentially every kind of metadata should be preserved here! This
534       // routine is supposed to clone a store instruction changing *only its
535       // type*. The only metadata it makes sense to drop is metadata which is
536       // invalidated when the pointer type changes. This should essentially
537       // never be the case in LLVM, but we explicitly switch over only known
538       // metadata to be conservatively correct. If you are adding metadata to
539       // LLVM which pertains to stores, you almost certainly want to add it
540       // here.
541       switch (ID) {
542       case LLVMContext::MD_dbg:
543       case LLVMContext::MD_tbaa:
544       case LLVMContext::MD_prof:
545       case LLVMContext::MD_fpmath:
546       case LLVMContext::MD_tbaa_struct:
547       case LLVMContext::MD_alias_scope:
548       case LLVMContext::MD_noalias:
549       case LLVMContext::MD_nontemporal:
550       case LLVMContext::MD_mem_parallel_loop_access:
551       case LLVMContext::MD_nonnull:
552         // All of these directly apply.
553         NewStore->setMetadata(ID, N);
554         break;
555
556       case LLVMContext::MD_invariant_load:
557       case LLVMContext::MD_range:
558         break;
559       }
560     }
561     return true;
562   }
563
564   // FIXME: We should also canonicalize loads of vectors when their elements are
565   // cast to other types.
566   return false;
567 }
568
569 /// equivalentAddressValues - Test if A and B will obviously have the same
570 /// value. This includes recognizing that %t0 and %t1 will have the same
571 /// value in code like this:
572 ///   %t0 = getelementptr \@a, 0, 3
573 ///   store i32 0, i32* %t0
574 ///   %t1 = getelementptr \@a, 0, 3
575 ///   %t2 = load i32* %t1
576 ///
577 static bool equivalentAddressValues(Value *A, Value *B) {
578   // Test if the values are trivially equivalent.
579   if (A == B) return true;
580
581   // Test if the values come form identical arithmetic instructions.
582   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
583   // its only used to compare two uses within the same basic block, which
584   // means that they'll always either have the same value or one of them
585   // will have an undefined value.
586   if (isa<BinaryOperator>(A) ||
587       isa<CastInst>(A) ||
588       isa<PHINode>(A) ||
589       isa<GetElementPtrInst>(A))
590     if (Instruction *BI = dyn_cast<Instruction>(B))
591       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
592         return true;
593
594   // Otherwise they may not be equivalent.
595   return false;
596 }
597
598 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
599   Value *Val = SI.getOperand(0);
600   Value *Ptr = SI.getOperand(1);
601
602   // Try to canonicalize the stored type.
603   if (combineStoreToValueType(*this, SI))
604     return EraseInstFromFunction(SI);
605
606   // Attempt to improve the alignment.
607   if (DL) {
608     unsigned KnownAlign = getOrEnforceKnownAlignment(
609         Ptr, DL->getPrefTypeAlignment(Val->getType()), DL, AC, &SI, DT);
610     unsigned StoreAlign = SI.getAlignment();
611     unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
612       DL->getABITypeAlignment(Val->getType());
613
614     if (KnownAlign > EffectiveStoreAlign)
615       SI.setAlignment(KnownAlign);
616     else if (StoreAlign == 0)
617       SI.setAlignment(EffectiveStoreAlign);
618   }
619
620   // Don't hack volatile/atomic stores.
621   // FIXME: Some bits are legal for atomic stores; needs refactoring.
622   if (!SI.isSimple()) return nullptr;
623
624   // If the RHS is an alloca with a single use, zapify the store, making the
625   // alloca dead.
626   if (Ptr->hasOneUse()) {
627     if (isa<AllocaInst>(Ptr))
628       return EraseInstFromFunction(SI);
629     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
630       if (isa<AllocaInst>(GEP->getOperand(0))) {
631         if (GEP->getOperand(0)->hasOneUse())
632           return EraseInstFromFunction(SI);
633       }
634     }
635   }
636
637   // Do really simple DSE, to catch cases where there are several consecutive
638   // stores to the same location, separated by a few arithmetic operations. This
639   // situation often occurs with bitfield accesses.
640   BasicBlock::iterator BBI = &SI;
641   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
642        --ScanInsts) {
643     --BBI;
644     // Don't count debug info directives, lest they affect codegen,
645     // and we skip pointer-to-pointer bitcasts, which are NOPs.
646     if (isa<DbgInfoIntrinsic>(BBI) ||
647         (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
648       ScanInsts++;
649       continue;
650     }
651
652     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
653       // Prev store isn't volatile, and stores to the same location?
654       if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
655                                                         SI.getOperand(1))) {
656         ++NumDeadStore;
657         ++BBI;
658         EraseInstFromFunction(*PrevSI);
659         continue;
660       }
661       break;
662     }
663
664     // If this is a load, we have to stop.  However, if the loaded value is from
665     // the pointer we're loading and is producing the pointer we're storing,
666     // then *this* store is dead (X = load P; store X -> P).
667     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
668       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
669           LI->isSimple())
670         return EraseInstFromFunction(SI);
671
672       // Otherwise, this is a load from some other location.  Stores before it
673       // may not be dead.
674       break;
675     }
676
677     // Don't skip over loads or things that can modify memory.
678     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
679       break;
680   }
681
682   // store X, null    -> turns into 'unreachable' in SimplifyCFG
683   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
684     if (!isa<UndefValue>(Val)) {
685       SI.setOperand(0, UndefValue::get(Val->getType()));
686       if (Instruction *U = dyn_cast<Instruction>(Val))
687         Worklist.Add(U);  // Dropped a use.
688     }
689     return nullptr;  // Do not modify these!
690   }
691
692   // store undef, Ptr -> noop
693   if (isa<UndefValue>(Val))
694     return EraseInstFromFunction(SI);
695
696   // If this store is the last instruction in the basic block (possibly
697   // excepting debug info instructions), and if the block ends with an
698   // unconditional branch, try to move it to the successor block.
699   BBI = &SI;
700   do {
701     ++BBI;
702   } while (isa<DbgInfoIntrinsic>(BBI) ||
703            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
704   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
705     if (BI->isUnconditional())
706       if (SimplifyStoreAtEndOfBlock(SI))
707         return nullptr;  // xform done!
708
709   return nullptr;
710 }
711
712 /// SimplifyStoreAtEndOfBlock - Turn things like:
713 ///   if () { *P = v1; } else { *P = v2 }
714 /// into a phi node with a store in the successor.
715 ///
716 /// Simplify things like:
717 ///   *P = v1; if () { *P = v2; }
718 /// into a phi node with a store in the successor.
719 ///
720 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
721   BasicBlock *StoreBB = SI.getParent();
722
723   // Check to see if the successor block has exactly two incoming edges.  If
724   // so, see if the other predecessor contains a store to the same location.
725   // if so, insert a PHI node (if needed) and move the stores down.
726   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
727
728   // Determine whether Dest has exactly two predecessors and, if so, compute
729   // the other predecessor.
730   pred_iterator PI = pred_begin(DestBB);
731   BasicBlock *P = *PI;
732   BasicBlock *OtherBB = nullptr;
733
734   if (P != StoreBB)
735     OtherBB = P;
736
737   if (++PI == pred_end(DestBB))
738     return false;
739
740   P = *PI;
741   if (P != StoreBB) {
742     if (OtherBB)
743       return false;
744     OtherBB = P;
745   }
746   if (++PI != pred_end(DestBB))
747     return false;
748
749   // Bail out if all the relevant blocks aren't distinct (this can happen,
750   // for example, if SI is in an infinite loop)
751   if (StoreBB == DestBB || OtherBB == DestBB)
752     return false;
753
754   // Verify that the other block ends in a branch and is not otherwise empty.
755   BasicBlock::iterator BBI = OtherBB->getTerminator();
756   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
757   if (!OtherBr || BBI == OtherBB->begin())
758     return false;
759
760   // If the other block ends in an unconditional branch, check for the 'if then
761   // else' case.  there is an instruction before the branch.
762   StoreInst *OtherStore = nullptr;
763   if (OtherBr->isUnconditional()) {
764     --BBI;
765     // Skip over debugging info.
766     while (isa<DbgInfoIntrinsic>(BBI) ||
767            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
768       if (BBI==OtherBB->begin())
769         return false;
770       --BBI;
771     }
772     // If this isn't a store, isn't a store to the same location, or is not the
773     // right kind of store, bail out.
774     OtherStore = dyn_cast<StoreInst>(BBI);
775     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
776         !SI.isSameOperationAs(OtherStore))
777       return false;
778   } else {
779     // Otherwise, the other block ended with a conditional branch. If one of the
780     // destinations is StoreBB, then we have the if/then case.
781     if (OtherBr->getSuccessor(0) != StoreBB &&
782         OtherBr->getSuccessor(1) != StoreBB)
783       return false;
784
785     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
786     // if/then triangle.  See if there is a store to the same ptr as SI that
787     // lives in OtherBB.
788     for (;; --BBI) {
789       // Check to see if we find the matching store.
790       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
791         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
792             !SI.isSameOperationAs(OtherStore))
793           return false;
794         break;
795       }
796       // If we find something that may be using or overwriting the stored
797       // value, or if we run out of instructions, we can't do the xform.
798       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
799           BBI == OtherBB->begin())
800         return false;
801     }
802
803     // In order to eliminate the store in OtherBr, we have to
804     // make sure nothing reads or overwrites the stored value in
805     // StoreBB.
806     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
807       // FIXME: This should really be AA driven.
808       if (I->mayReadFromMemory() || I->mayWriteToMemory())
809         return false;
810     }
811   }
812
813   // Insert a PHI node now if we need it.
814   Value *MergedVal = OtherStore->getOperand(0);
815   if (MergedVal != SI.getOperand(0)) {
816     PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
817     PN->addIncoming(SI.getOperand(0), SI.getParent());
818     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
819     MergedVal = InsertNewInstBefore(PN, DestBB->front());
820   }
821
822   // Advance to a place where it is safe to insert the new store and
823   // insert it.
824   BBI = DestBB->getFirstInsertionPt();
825   StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
826                                    SI.isVolatile(),
827                                    SI.getAlignment(),
828                                    SI.getOrdering(),
829                                    SI.getSynchScope());
830   InsertNewInstBefore(NewSI, *BBI);
831   NewSI->setDebugLoc(OtherStore->getDebugLoc());
832
833   // If the two stores had AA tags, merge them.
834   AAMDNodes AATags;
835   SI.getAAMetadata(AATags);
836   if (AATags) {
837     OtherStore->getAAMetadata(AATags, /* Merge = */ true);
838     NewSI->setAAMetadata(AATags);
839   }
840
841   // Nuke the old stores.
842   EraseInstFromFunction(SI);
843   EraseInstFromFunction(*OtherStore);
844   return true;
845 }