[Modules] Sink all the DEBUG_TYPE defines for InstCombine out of the
[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 #define DEBUG_TYPE "instcombine"
15 #include "InstCombine.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/Loads.h"
18 #include "llvm/IR/DataLayout.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 STATISTIC(NumDeadStore,    "Number of dead stores eliminated");
25 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
26
27 /// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
28 /// some part of a constant global variable.  This intentionally only accepts
29 /// constant expressions because we can't rewrite arbitrary instructions.
30 static bool pointsToConstantGlobal(Value *V) {
31   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
32     return GV->isConstant();
33   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
34     if (CE->getOpcode() == Instruction::BitCast ||
35         CE->getOpcode() == Instruction::GetElementPtr)
36       return pointsToConstantGlobal(CE->getOperand(0));
37   return false;
38 }
39
40 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
41 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
42 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
43 /// track of whether it moves the pointer (with IsOffset) but otherwise traverse
44 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
45 /// the alloca, and if the source pointer is a pointer to a constant global, we
46 /// can optimize this.
47 static bool
48 isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
49                                SmallVectorImpl<Instruction *> &ToDelete,
50                                bool IsOffset = false) {
51   // We track lifetime intrinsics as we encounter them.  If we decide to go
52   // ahead and replace the value with the global, this lets the caller quickly
53   // eliminate the markers.
54
55   for (Use &U : V->uses()) {
56     Instruction *I = cast<Instruction>(U.getUser());
57
58     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
59       // Ignore non-volatile loads, they are always ok.
60       if (!LI->isSimple()) return false;
61       continue;
62     }
63
64     if (BitCastInst *BCI = dyn_cast<BitCastInst>(I)) {
65       // If uses of the bitcast are ok, we are ok.
66       if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, ToDelete, IsOffset))
67         return false;
68       continue;
69     }
70     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
71       // If the GEP has all zero indices, it doesn't offset the pointer.  If it
72       // doesn't, it does.
73       if (!isOnlyCopiedFromConstantGlobal(
74               GEP, TheCopy, ToDelete, IsOffset || !GEP->hasAllZeroIndices()))
75         return false;
76       continue;
77     }
78
79     if (CallSite CS = I) {
80       // If this is the function being called then we treat it like a load and
81       // ignore it.
82       if (CS.isCallee(&U))
83         continue;
84
85       // Inalloca arguments are clobbered by the call.
86       unsigned ArgNo = CS.getArgumentNo(&U);
87       if (CS.isInAllocaArgument(ArgNo))
88         return false;
89
90       // If this is a readonly/readnone call site, then we know it is just a
91       // load (but one that potentially returns the value itself), so we can
92       // ignore it if we know that the value isn't captured.
93       if (CS.onlyReadsMemory() &&
94           (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
95         continue;
96
97       // If this is being passed as a byval argument, the caller is making a
98       // copy, so it is only a read of the alloca.
99       if (CS.isByValArgument(ArgNo))
100         continue;
101     }
102
103     // Lifetime intrinsics can be handled by the caller.
104     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
105       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
106           II->getIntrinsicID() == Intrinsic::lifetime_end) {
107         assert(II->use_empty() && "Lifetime markers have no result to use!");
108         ToDelete.push_back(II);
109         continue;
110       }
111     }
112
113     // If this is isn't our memcpy/memmove, reject it as something we can't
114     // handle.
115     MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
116     if (MI == 0)
117       return false;
118
119     // If the transfer is using the alloca as a source of the transfer, then
120     // ignore it since it is a load (unless the transfer is volatile).
121     if (U.getOperandNo() == 1) {
122       if (MI->isVolatile()) return false;
123       continue;
124     }
125
126     // If we already have seen a copy, reject the second one.
127     if (TheCopy) return false;
128
129     // If the pointer has been offset from the start of the alloca, we can't
130     // safely handle this.
131     if (IsOffset) return false;
132
133     // If the memintrinsic isn't using the alloca as the dest, reject it.
134     if (U.getOperandNo() != 0) return false;
135
136     // If the source of the memcpy/move is not a constant global, reject it.
137     if (!pointsToConstantGlobal(MI->getSource()))
138       return false;
139
140     // Otherwise, the transform is safe.  Remember the copy instruction.
141     TheCopy = MI;
142   }
143   return true;
144 }
145
146 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
147 /// modified by a copy from a constant global.  If we can prove this, we can
148 /// replace any uses of the alloca with uses of the global directly.
149 static MemTransferInst *
150 isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
151                                SmallVectorImpl<Instruction *> &ToDelete) {
152   MemTransferInst *TheCopy = 0;
153   if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
154     return TheCopy;
155   return 0;
156 }
157
158 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
159   // Ensure that the alloca array size argument has type intptr_t, so that
160   // any casting is exposed early.
161   if (DL) {
162     Type *IntPtrTy = DL->getIntPtrType(AI.getType());
163     if (AI.getArraySize()->getType() != IntPtrTy) {
164       Value *V = Builder->CreateIntCast(AI.getArraySize(),
165                                         IntPtrTy, false);
166       AI.setOperand(0, V);
167       return &AI;
168     }
169   }
170
171   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
172   if (AI.isArrayAllocation()) {  // Check C != 1
173     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
174       Type *NewTy =
175         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
176       AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
177       New->setAlignment(AI.getAlignment());
178
179       // Scan to the end of the allocation instructions, to skip over a block of
180       // allocas if possible...also skip interleaved debug info
181       //
182       BasicBlock::iterator It = New;
183       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
184
185       // Now that I is pointing to the first non-allocation-inst in the block,
186       // insert our getelementptr instruction...
187       //
188       Type *IdxTy = DL
189                   ? DL->getIntPtrType(AI.getType())
190                   : Type::getInt64Ty(AI.getContext());
191       Value *NullIdx = Constant::getNullValue(IdxTy);
192       Value *Idx[2] = { NullIdx, NullIdx };
193       Instruction *GEP =
194         GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
195       InsertNewInstBefore(GEP, *It);
196
197       // Now make everything use the getelementptr instead of the original
198       // allocation.
199       return ReplaceInstUsesWith(AI, GEP);
200     } else if (isa<UndefValue>(AI.getArraySize())) {
201       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
202     }
203   }
204
205   if (DL && AI.getAllocatedType()->isSized()) {
206     // If the alignment is 0 (unspecified), assign it the preferred alignment.
207     if (AI.getAlignment() == 0)
208       AI.setAlignment(DL->getPrefTypeAlignment(AI.getAllocatedType()));
209
210     // Move all alloca's of zero byte objects to the entry block and merge them
211     // together.  Note that we only do this for alloca's, because malloc should
212     // allocate and return a unique pointer, even for a zero byte allocation.
213     if (DL->getTypeAllocSize(AI.getAllocatedType()) == 0) {
214       // For a zero sized alloca there is no point in doing an array allocation.
215       // This is helpful if the array size is a complicated expression not used
216       // elsewhere.
217       if (AI.isArrayAllocation()) {
218         AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
219         return &AI;
220       }
221
222       // Get the first instruction in the entry block.
223       BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
224       Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
225       if (FirstInst != &AI) {
226         // If the entry block doesn't start with a zero-size alloca then move
227         // this one to the start of the entry block.  There is no problem with
228         // dominance as the array size was forced to a constant earlier already.
229         AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
230         if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
231             DL->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
232           AI.moveBefore(FirstInst);
233           return &AI;
234         }
235
236         // If the alignment of the entry block alloca is 0 (unspecified),
237         // assign it the preferred alignment.
238         if (EntryAI->getAlignment() == 0)
239           EntryAI->setAlignment(
240             DL->getPrefTypeAlignment(EntryAI->getAllocatedType()));
241         // Replace this zero-sized alloca with the one at the start of the entry
242         // block after ensuring that the address will be aligned enough for both
243         // types.
244         unsigned MaxAlign = std::max(EntryAI->getAlignment(),
245                                      AI.getAlignment());
246         EntryAI->setAlignment(MaxAlign);
247         if (AI.getType() != EntryAI->getType())
248           return new BitCastInst(EntryAI, AI.getType());
249         return ReplaceInstUsesWith(AI, EntryAI);
250       }
251     }
252   }
253
254   if (AI.getAlignment()) {
255     // Check to see if this allocation is only modified by a memcpy/memmove from
256     // a constant global whose alignment is equal to or exceeds that of the
257     // allocation.  If this is the case, we can change all users to use
258     // the constant global instead.  This is commonly produced by the CFE by
259     // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
260     // is only subsequently read.
261     SmallVector<Instruction *, 4> ToDelete;
262     if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
263       unsigned SourceAlign = getOrEnforceKnownAlignment(Copy->getSource(),
264                                                         AI.getAlignment(), DL);
265       if (AI.getAlignment() <= SourceAlign) {
266         DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
267         DEBUG(dbgs() << "  memcpy = " << *Copy << '\n');
268         for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
269           EraseInstFromFunction(*ToDelete[i]);
270         Constant *TheSrc = cast<Constant>(Copy->getSource());
271         Constant *Cast
272           = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
273         Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
274         EraseInstFromFunction(*Copy);
275         ++NumGlobalCopies;
276         return NewI;
277       }
278     }
279   }
280
281   // At last, use the generic allocation site handler to aggressively remove
282   // unused allocas.
283   return visitAllocSite(AI);
284 }
285
286
287 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
288 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
289                                         const DataLayout *DL) {
290   User *CI = cast<User>(LI.getOperand(0));
291   Value *CastOp = CI->getOperand(0);
292
293   PointerType *DestTy = cast<PointerType>(CI->getType());
294   Type *DestPTy = DestTy->getElementType();
295   if (PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
296
297     // If the address spaces don't match, don't eliminate the cast.
298     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
299       return 0;
300
301     Type *SrcPTy = SrcTy->getElementType();
302
303     if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() ||
304          DestPTy->isVectorTy()) {
305       // If the source is an array, the code below will not succeed.  Check to
306       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
307       // constants.
308       if (ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
309         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
310           if (ASrcTy->getNumElements() != 0) {
311             Type *IdxTy = DL
312                         ? DL->getIntPtrType(SrcTy)
313                         : Type::getInt64Ty(SrcTy->getContext());
314             Value *Idx = Constant::getNullValue(IdxTy);
315             Value *Idxs[2] = { Idx, Idx };
316             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
317             SrcTy = cast<PointerType>(CastOp->getType());
318             SrcPTy = SrcTy->getElementType();
319           }
320
321       if (IC.getDataLayout() &&
322           (SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() ||
323             SrcPTy->isVectorTy()) &&
324           // Do not allow turning this into a load of an integer, which is then
325           // casted to a pointer, this pessimizes pointer analysis a lot.
326           (SrcPTy->isPtrOrPtrVectorTy() ==
327            LI.getType()->isPtrOrPtrVectorTy()) &&
328           IC.getDataLayout()->getTypeSizeInBits(SrcPTy) ==
329                IC.getDataLayout()->getTypeSizeInBits(DestPTy)) {
330
331         // Okay, we are casting from one integer or pointer type to another of
332         // the same size.  Instead of casting the pointer before the load, cast
333         // the result of the loaded value.
334         LoadInst *NewLoad =
335           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
336         NewLoad->setAlignment(LI.getAlignment());
337         NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
338         // Now cast the result of the load.
339         PointerType *OldTy = dyn_cast<PointerType>(NewLoad->getType());
340         PointerType *NewTy = dyn_cast<PointerType>(LI.getType());
341         if (OldTy && NewTy &&
342             OldTy->getAddressSpace() != NewTy->getAddressSpace()) {
343           return new AddrSpaceCastInst(NewLoad, LI.getType());
344         }
345
346         return new BitCastInst(NewLoad, LI.getType());
347       }
348     }
349   }
350   return 0;
351 }
352
353 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
354   Value *Op = LI.getOperand(0);
355
356   // Attempt to improve the alignment.
357   if (DL) {
358     unsigned KnownAlign =
359       getOrEnforceKnownAlignment(Op, DL->getPrefTypeAlignment(LI.getType()),DL);
360     unsigned LoadAlign = LI.getAlignment();
361     unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
362       DL->getABITypeAlignment(LI.getType());
363
364     if (KnownAlign > EffectiveLoadAlign)
365       LI.setAlignment(KnownAlign);
366     else if (LoadAlign == 0)
367       LI.setAlignment(EffectiveLoadAlign);
368   }
369
370   // load (cast X) --> cast (load X) iff safe.
371   if (isa<CastInst>(Op))
372     if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
373       return Res;
374
375   // None of the following transforms are legal for volatile/atomic loads.
376   // FIXME: Some of it is okay for atomic loads; needs refactoring.
377   if (!LI.isSimple()) return 0;
378
379   // Do really simple store-to-load forwarding and load CSE, to catch cases
380   // where there are several consecutive memory accesses to the same location,
381   // separated by a few arithmetic operations.
382   BasicBlock::iterator BBI = &LI;
383   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
384     return ReplaceInstUsesWith(LI, AvailableVal);
385
386   // load(gep null, ...) -> unreachable
387   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
388     const Value *GEPI0 = GEPI->getOperand(0);
389     // TODO: Consider a target hook for valid address spaces for this xform.
390     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
391       // Insert a new store to null instruction before the load to indicate
392       // that this code is not reachable.  We do this instead of inserting
393       // an unreachable instruction directly because we cannot modify the
394       // CFG.
395       new StoreInst(UndefValue::get(LI.getType()),
396                     Constant::getNullValue(Op->getType()), &LI);
397       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
398     }
399   }
400
401   // load null/undef -> unreachable
402   // TODO: Consider a target hook for valid address spaces for this xform.
403   if (isa<UndefValue>(Op) ||
404       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
405     // Insert a new store to null instruction before the load to indicate that
406     // this code is not reachable.  We do this instead of inserting an
407     // unreachable instruction directly because we cannot modify the CFG.
408     new StoreInst(UndefValue::get(LI.getType()),
409                   Constant::getNullValue(Op->getType()), &LI);
410     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
411   }
412
413   // Instcombine load (constantexpr_cast global) -> cast (load global)
414   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
415     if (CE->isCast())
416       if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
417         return Res;
418
419   if (Op->hasOneUse()) {
420     // Change select and PHI nodes to select values instead of addresses: this
421     // helps alias analysis out a lot, allows many others simplifications, and
422     // exposes redundancy in the code.
423     //
424     // Note that we cannot do the transformation unless we know that the
425     // introduced loads cannot trap!  Something like this is valid as long as
426     // the condition is always false: load (select bool %C, int* null, int* %G),
427     // but it would not be valid if we transformed it to load from null
428     // unconditionally.
429     //
430     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
431       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
432       unsigned Align = LI.getAlignment();
433       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
434           isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
435         LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
436                                            SI->getOperand(1)->getName()+".val");
437         LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
438                                            SI->getOperand(2)->getName()+".val");
439         V1->setAlignment(Align);
440         V2->setAlignment(Align);
441         return SelectInst::Create(SI->getCondition(), V1, V2);
442       }
443
444       // load (select (cond, null, P)) -> load P
445       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
446         if (C->isNullValue()) {
447           LI.setOperand(0, SI->getOperand(2));
448           return &LI;
449         }
450
451       // load (select (cond, P, null)) -> load P
452       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
453         if (C->isNullValue()) {
454           LI.setOperand(0, SI->getOperand(1));
455           return &LI;
456         }
457     }
458   }
459   return 0;
460 }
461
462 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
463 /// when possible.  This makes it generally easy to do alias analysis and/or
464 /// SROA/mem2reg of the memory object.
465 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
466   User *CI = cast<User>(SI.getOperand(1));
467   Value *CastOp = CI->getOperand(0);
468
469   Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
470   PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
471   if (SrcTy == 0) return 0;
472
473   Type *SrcPTy = SrcTy->getElementType();
474
475   if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
476     return 0;
477
478   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
479   /// to its first element.  This allows us to handle things like:
480   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
481   /// on 32-bit hosts.
482   SmallVector<Value*, 4> NewGEPIndices;
483
484   // If the source is an array, the code below will not succeed.  Check to
485   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
486   // constants.
487   if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
488     // Index through pointer.
489     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
490     NewGEPIndices.push_back(Zero);
491
492     while (1) {
493       if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
494         if (!STy->getNumElements()) /* Struct can be empty {} */
495           break;
496         NewGEPIndices.push_back(Zero);
497         SrcPTy = STy->getElementType(0);
498       } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
499         NewGEPIndices.push_back(Zero);
500         SrcPTy = ATy->getElementType();
501       } else {
502         break;
503       }
504     }
505
506     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
507   }
508
509   if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
510     return 0;
511
512   // If the pointers point into different address spaces don't do the
513   // transformation.
514   if (SrcTy->getAddressSpace() !=
515       cast<PointerType>(CI->getType())->getAddressSpace())
516     return 0;
517
518   // If the pointers point to values of different sizes don't do the
519   // transformation.
520   if (!IC.getDataLayout() ||
521       IC.getDataLayout()->getTypeSizeInBits(SrcPTy) !=
522       IC.getDataLayout()->getTypeSizeInBits(DestPTy))
523     return 0;
524
525   // If the pointers point to pointers to different address spaces don't do the
526   // transformation. It is not safe to introduce an addrspacecast instruction in
527   // this case since, depending on the target, addrspacecast may not be a no-op
528   // cast.
529   if (SrcPTy->isPointerTy() && DestPTy->isPointerTy() &&
530       SrcPTy->getPointerAddressSpace() != DestPTy->getPointerAddressSpace())
531     return 0;
532
533   // Okay, we are casting from one integer or pointer type to another of
534   // the same size.  Instead of casting the pointer before
535   // the store, cast the value to be stored.
536   Value *NewCast;
537   Instruction::CastOps opcode = Instruction::BitCast;
538   Type* CastSrcTy = DestPTy;
539   Type* CastDstTy = SrcPTy;
540   if (CastDstTy->isPointerTy()) {
541     if (CastSrcTy->isIntegerTy())
542       opcode = Instruction::IntToPtr;
543   } else if (CastDstTy->isIntegerTy()) {
544     if (CastSrcTy->isPointerTy())
545       opcode = Instruction::PtrToInt;
546   }
547
548   // SIOp0 is a pointer to aggregate and this is a store to the first field,
549   // emit a GEP to index into its first field.
550   if (!NewGEPIndices.empty())
551     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
552
553   Value *SIOp0 = SI.getOperand(0);
554   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
555                                    SIOp0->getName()+".c");
556   SI.setOperand(0, NewCast);
557   SI.setOperand(1, CastOp);
558   return &SI;
559 }
560
561 /// equivalentAddressValues - Test if A and B will obviously have the same
562 /// value. This includes recognizing that %t0 and %t1 will have the same
563 /// value in code like this:
564 ///   %t0 = getelementptr \@a, 0, 3
565 ///   store i32 0, i32* %t0
566 ///   %t1 = getelementptr \@a, 0, 3
567 ///   %t2 = load i32* %t1
568 ///
569 static bool equivalentAddressValues(Value *A, Value *B) {
570   // Test if the values are trivially equivalent.
571   if (A == B) return true;
572
573   // Test if the values come form identical arithmetic instructions.
574   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
575   // its only used to compare two uses within the same basic block, which
576   // means that they'll always either have the same value or one of them
577   // will have an undefined value.
578   if (isa<BinaryOperator>(A) ||
579       isa<CastInst>(A) ||
580       isa<PHINode>(A) ||
581       isa<GetElementPtrInst>(A))
582     if (Instruction *BI = dyn_cast<Instruction>(B))
583       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
584         return true;
585
586   // Otherwise they may not be equivalent.
587   return false;
588 }
589
590 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
591   Value *Val = SI.getOperand(0);
592   Value *Ptr = SI.getOperand(1);
593
594   // Attempt to improve the alignment.
595   if (DL) {
596     unsigned KnownAlign =
597       getOrEnforceKnownAlignment(Ptr, DL->getPrefTypeAlignment(Val->getType()),
598                                  DL);
599     unsigned StoreAlign = SI.getAlignment();
600     unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
601       DL->getABITypeAlignment(Val->getType());
602
603     if (KnownAlign > EffectiveStoreAlign)
604       SI.setAlignment(KnownAlign);
605     else if (StoreAlign == 0)
606       SI.setAlignment(EffectiveStoreAlign);
607   }
608
609   // Don't hack volatile/atomic stores.
610   // FIXME: Some bits are legal for atomic stores; needs refactoring.
611   if (!SI.isSimple()) return 0;
612
613   // If the RHS is an alloca with a single use, zapify the store, making the
614   // alloca dead.
615   if (Ptr->hasOneUse()) {
616     if (isa<AllocaInst>(Ptr))
617       return EraseInstFromFunction(SI);
618     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
619       if (isa<AllocaInst>(GEP->getOperand(0))) {
620         if (GEP->getOperand(0)->hasOneUse())
621           return EraseInstFromFunction(SI);
622       }
623     }
624   }
625
626   // Do really simple DSE, to catch cases where there are several consecutive
627   // stores to the same location, separated by a few arithmetic operations. This
628   // situation often occurs with bitfield accesses.
629   BasicBlock::iterator BBI = &SI;
630   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
631        --ScanInsts) {
632     --BBI;
633     // Don't count debug info directives, lest they affect codegen,
634     // and we skip pointer-to-pointer bitcasts, which are NOPs.
635     if (isa<DbgInfoIntrinsic>(BBI) ||
636         (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
637       ScanInsts++;
638       continue;
639     }
640
641     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
642       // Prev store isn't volatile, and stores to the same location?
643       if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
644                                                         SI.getOperand(1))) {
645         ++NumDeadStore;
646         ++BBI;
647         EraseInstFromFunction(*PrevSI);
648         continue;
649       }
650       break;
651     }
652
653     // If this is a load, we have to stop.  However, if the loaded value is from
654     // the pointer we're loading and is producing the pointer we're storing,
655     // then *this* store is dead (X = load P; store X -> P).
656     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
657       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
658           LI->isSimple())
659         return EraseInstFromFunction(SI);
660
661       // Otherwise, this is a load from some other location.  Stores before it
662       // may not be dead.
663       break;
664     }
665
666     // Don't skip over loads or things that can modify memory.
667     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
668       break;
669   }
670
671   // store X, null    -> turns into 'unreachable' in SimplifyCFG
672   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
673     if (!isa<UndefValue>(Val)) {
674       SI.setOperand(0, UndefValue::get(Val->getType()));
675       if (Instruction *U = dyn_cast<Instruction>(Val))
676         Worklist.Add(U);  // Dropped a use.
677     }
678     return 0;  // Do not modify these!
679   }
680
681   // store undef, Ptr -> noop
682   if (isa<UndefValue>(Val))
683     return EraseInstFromFunction(SI);
684
685   // If the pointer destination is a cast, see if we can fold the cast into the
686   // source instead.
687   if (isa<CastInst>(Ptr))
688     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
689       return Res;
690   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
691     if (CE->isCast())
692       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
693         return Res;
694
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 0;  // xform done!
708
709   return 0;
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 = 0;
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 = 0;
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 the same TBAA tag, preserve it.
834   if (MDNode *TBAATag = SI.getMetadata(LLVMContext::MD_tbaa))
835     if ((TBAATag = MDNode::getMostGenericTBAA(TBAATag,
836                                OtherStore->getMetadata(LLVMContext::MD_tbaa))))
837       NewSI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
838
839
840   // Nuke the old stores.
841   EraseInstFromFunction(SI);
842   EraseInstFromFunction(*OtherStore);
843   return true;
844 }