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