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