Convert IRBuilder::CreateGEP and IRBuilder::CreateInBoundsGEP to use
[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/Target/TargetData.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
25 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
26   // Ensure that the alloca array size argument has type intptr_t, so that
27   // any casting is exposed early.
28   if (TD) {
29     Type *IntPtrTy = TD->getIntPtrType(AI.getContext());
30     if (AI.getArraySize()->getType() != IntPtrTy) {
31       Value *V = Builder->CreateIntCast(AI.getArraySize(),
32                                         IntPtrTy, false);
33       AI.setOperand(0, V);
34       return &AI;
35     }
36   }
37
38   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
39   if (AI.isArrayAllocation()) {  // Check C != 1
40     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
41       Type *NewTy = 
42         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
43       assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
44       AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
45       New->setAlignment(AI.getAlignment());
46
47       // Scan to the end of the allocation instructions, to skip over a block of
48       // allocas if possible...also skip interleaved debug info
49       //
50       BasicBlock::iterator It = New;
51       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
52
53       // Now that I is pointing to the first non-allocation-inst in the block,
54       // insert our getelementptr instruction...
55       //
56       Value *NullIdx =Constant::getNullValue(Type::getInt32Ty(AI.getContext()));
57       Value *Idx[2];
58       Idx[0] = NullIdx;
59       Idx[1] = NullIdx;
60       Instruction *GEP =
61            GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
62                                              New->getName()+".sub");
63       InsertNewInstBefore(GEP, *It);
64
65       // Now make everything use the getelementptr instead of the original
66       // allocation.
67       return ReplaceInstUsesWith(AI, GEP);
68     } else if (isa<UndefValue>(AI.getArraySize())) {
69       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
70     }
71   }
72
73   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
74     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
75     // Note that we only do this for alloca's, because malloc should allocate
76     // and return a unique pointer, even for a zero byte allocation.
77     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
78       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
79
80     // If the alignment is 0 (unspecified), assign it the preferred alignment.
81     if (AI.getAlignment() == 0)
82       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
83   }
84
85   return 0;
86 }
87
88
89 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
90 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
91                                         const TargetData *TD) {
92   User *CI = cast<User>(LI.getOperand(0));
93   Value *CastOp = CI->getOperand(0);
94
95   PointerType *DestTy = cast<PointerType>(CI->getType());
96   Type *DestPTy = DestTy->getElementType();
97   if (PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
98
99     // If the address spaces don't match, don't eliminate the cast.
100     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
101       return 0;
102
103     Type *SrcPTy = SrcTy->getElementType();
104
105     if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() || 
106          DestPTy->isVectorTy()) {
107       // If the source is an array, the code below will not succeed.  Check to
108       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
109       // constants.
110       if (ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
111         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
112           if (ASrcTy->getNumElements() != 0) {
113             Value *Idxs[2];
114             Idxs[0] = Constant::getNullValue(Type::getInt32Ty(LI.getContext()));
115             Idxs[1] = Idxs[0];
116             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
117             SrcTy = cast<PointerType>(CastOp->getType());
118             SrcPTy = SrcTy->getElementType();
119           }
120
121       if (IC.getTargetData() &&
122           (SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() || 
123             SrcPTy->isVectorTy()) &&
124           // Do not allow turning this into a load of an integer, which is then
125           // casted to a pointer, this pessimizes pointer analysis a lot.
126           (SrcPTy->isPointerTy() == LI.getType()->isPointerTy()) &&
127           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
128                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
129
130         // Okay, we are casting from one integer or pointer type to another of
131         // the same size.  Instead of casting the pointer before the load, cast
132         // the result of the loaded value.
133         LoadInst *NewLoad = 
134           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
135         NewLoad->setAlignment(LI.getAlignment());
136         // Now cast the result of the load.
137         return new BitCastInst(NewLoad, LI.getType());
138       }
139     }
140   }
141   return 0;
142 }
143
144 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
145   Value *Op = LI.getOperand(0);
146
147   // Attempt to improve the alignment.
148   if (TD) {
149     unsigned KnownAlign =
150       getOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()),TD);
151     unsigned LoadAlign = LI.getAlignment();
152     unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
153       TD->getABITypeAlignment(LI.getType());
154
155     if (KnownAlign > EffectiveLoadAlign)
156       LI.setAlignment(KnownAlign);
157     else if (LoadAlign == 0)
158       LI.setAlignment(EffectiveLoadAlign);
159   }
160
161   // load (cast X) --> cast (load X) iff safe.
162   if (isa<CastInst>(Op))
163     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
164       return Res;
165
166   // None of the following transforms are legal for volatile loads.
167   if (LI.isVolatile()) return 0;
168   
169   // Do really simple store-to-load forwarding and load CSE, to catch cases
170   // where there are several consecutive memory accesses to the same location,
171   // separated by a few arithmetic operations.
172   BasicBlock::iterator BBI = &LI;
173   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
174     return ReplaceInstUsesWith(LI, AvailableVal);
175
176   // load(gep null, ...) -> unreachable
177   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
178     const Value *GEPI0 = GEPI->getOperand(0);
179     // TODO: Consider a target hook for valid address spaces for this xform.
180     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
181       // Insert a new store to null instruction before the load to indicate
182       // that this code is not reachable.  We do this instead of inserting
183       // an unreachable instruction directly because we cannot modify the
184       // CFG.
185       new StoreInst(UndefValue::get(LI.getType()),
186                     Constant::getNullValue(Op->getType()), &LI);
187       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
188     }
189   } 
190
191   // load null/undef -> unreachable
192   // TODO: Consider a target hook for valid address spaces for this xform.
193   if (isa<UndefValue>(Op) ||
194       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
195     // Insert a new store to null instruction before the load to indicate that
196     // this code is not reachable.  We do this instead of inserting an
197     // unreachable instruction directly because we cannot modify the CFG.
198     new StoreInst(UndefValue::get(LI.getType()),
199                   Constant::getNullValue(Op->getType()), &LI);
200     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
201   }
202
203   // Instcombine load (constantexpr_cast global) -> cast (load global)
204   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
205     if (CE->isCast())
206       if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
207         return Res;
208   
209   if (Op->hasOneUse()) {
210     // Change select and PHI nodes to select values instead of addresses: this
211     // helps alias analysis out a lot, allows many others simplifications, and
212     // exposes redundancy in the code.
213     //
214     // Note that we cannot do the transformation unless we know that the
215     // introduced loads cannot trap!  Something like this is valid as long as
216     // the condition is always false: load (select bool %C, int* null, int* %G),
217     // but it would not be valid if we transformed it to load from null
218     // unconditionally.
219     //
220     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
221       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
222       unsigned Align = LI.getAlignment();
223       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, TD) &&
224           isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, TD)) {
225         LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
226                                            SI->getOperand(1)->getName()+".val");
227         LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
228                                            SI->getOperand(2)->getName()+".val");
229         V1->setAlignment(Align);
230         V2->setAlignment(Align);
231         return SelectInst::Create(SI->getCondition(), V1, V2);
232       }
233
234       // load (select (cond, null, P)) -> load P
235       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
236         if (C->isNullValue()) {
237           LI.setOperand(0, SI->getOperand(2));
238           return &LI;
239         }
240
241       // load (select (cond, P, null)) -> load P
242       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
243         if (C->isNullValue()) {
244           LI.setOperand(0, SI->getOperand(1));
245           return &LI;
246         }
247     }
248   }
249   return 0;
250 }
251
252 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
253 /// when possible.  This makes it generally easy to do alias analysis and/or
254 /// SROA/mem2reg of the memory object.
255 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
256   User *CI = cast<User>(SI.getOperand(1));
257   Value *CastOp = CI->getOperand(0);
258
259   Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
260   PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
261   if (SrcTy == 0) return 0;
262   
263   Type *SrcPTy = SrcTy->getElementType();
264
265   if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
266     return 0;
267   
268   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
269   /// to its first element.  This allows us to handle things like:
270   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
271   /// on 32-bit hosts.
272   SmallVector<Value*, 4> NewGEPIndices;
273   
274   // If the source is an array, the code below will not succeed.  Check to
275   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
276   // constants.
277   if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
278     // Index through pointer.
279     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
280     NewGEPIndices.push_back(Zero);
281     
282     while (1) {
283       if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
284         if (!STy->getNumElements()) /* Struct can be empty {} */
285           break;
286         NewGEPIndices.push_back(Zero);
287         SrcPTy = STy->getElementType(0);
288       } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
289         NewGEPIndices.push_back(Zero);
290         SrcPTy = ATy->getElementType();
291       } else {
292         break;
293       }
294     }
295     
296     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
297   }
298
299   if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
300     return 0;
301   
302   // If the pointers point into different address spaces or if they point to
303   // values with different sizes, we can't do the transformation.
304   if (!IC.getTargetData() ||
305       SrcTy->getAddressSpace() != 
306         cast<PointerType>(CI->getType())->getAddressSpace() ||
307       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
308       IC.getTargetData()->getTypeSizeInBits(DestPTy))
309     return 0;
310
311   // Okay, we are casting from one integer or pointer type to another of
312   // the same size.  Instead of casting the pointer before 
313   // the store, cast the value to be stored.
314   Value *NewCast;
315   Value *SIOp0 = SI.getOperand(0);
316   Instruction::CastOps opcode = Instruction::BitCast;
317   Type* CastSrcTy = SIOp0->getType();
318   Type* CastDstTy = SrcPTy;
319   if (CastDstTy->isPointerTy()) {
320     if (CastSrcTy->isIntegerTy())
321       opcode = Instruction::IntToPtr;
322   } else if (CastDstTy->isIntegerTy()) {
323     if (SIOp0->getType()->isPointerTy())
324       opcode = Instruction::PtrToInt;
325   }
326   
327   // SIOp0 is a pointer to aggregate and this is a store to the first field,
328   // emit a GEP to index into its first field.
329   if (!NewGEPIndices.empty())
330     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
331   
332   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
333                                    SIOp0->getName()+".c");
334   SI.setOperand(0, NewCast);
335   SI.setOperand(1, CastOp);
336   return &SI;
337 }
338
339 /// equivalentAddressValues - Test if A and B will obviously have the same
340 /// value. This includes recognizing that %t0 and %t1 will have the same
341 /// value in code like this:
342 ///   %t0 = getelementptr \@a, 0, 3
343 ///   store i32 0, i32* %t0
344 ///   %t1 = getelementptr \@a, 0, 3
345 ///   %t2 = load i32* %t1
346 ///
347 static bool equivalentAddressValues(Value *A, Value *B) {
348   // Test if the values are trivially equivalent.
349   if (A == B) return true;
350   
351   // Test if the values come form identical arithmetic instructions.
352   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
353   // its only used to compare two uses within the same basic block, which
354   // means that they'll always either have the same value or one of them
355   // will have an undefined value.
356   if (isa<BinaryOperator>(A) ||
357       isa<CastInst>(A) ||
358       isa<PHINode>(A) ||
359       isa<GetElementPtrInst>(A))
360     if (Instruction *BI = dyn_cast<Instruction>(B))
361       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
362         return true;
363   
364   // Otherwise they may not be equivalent.
365   return false;
366 }
367
368 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
369   Value *Val = SI.getOperand(0);
370   Value *Ptr = SI.getOperand(1);
371
372   // If the RHS is an alloca with a single use, zapify the store, making the
373   // alloca dead.
374   if (!SI.isVolatile()) {
375     if (Ptr->hasOneUse()) {
376       if (isa<AllocaInst>(Ptr)) 
377         return EraseInstFromFunction(SI);
378       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
379         if (isa<AllocaInst>(GEP->getOperand(0))) {
380           if (GEP->getOperand(0)->hasOneUse())
381             return EraseInstFromFunction(SI);
382         }
383       }
384     }
385   }
386
387   // Attempt to improve the alignment.
388   if (TD) {
389     unsigned KnownAlign =
390       getOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()),
391                                  TD);
392     unsigned StoreAlign = SI.getAlignment();
393     unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
394       TD->getABITypeAlignment(Val->getType());
395
396     if (KnownAlign > EffectiveStoreAlign)
397       SI.setAlignment(KnownAlign);
398     else if (StoreAlign == 0)
399       SI.setAlignment(EffectiveStoreAlign);
400   }
401
402   // Do really simple DSE, to catch cases where there are several consecutive
403   // stores to the same location, separated by a few arithmetic operations. This
404   // situation often occurs with bitfield accesses.
405   BasicBlock::iterator BBI = &SI;
406   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
407        --ScanInsts) {
408     --BBI;
409     // Don't count debug info directives, lest they affect codegen,
410     // and we skip pointer-to-pointer bitcasts, which are NOPs.
411     if (isa<DbgInfoIntrinsic>(BBI) ||
412         (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
413       ScanInsts++;
414       continue;
415     }    
416     
417     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
418       // Prev store isn't volatile, and stores to the same location?
419       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
420                                                           SI.getOperand(1))) {
421         ++NumDeadStore;
422         ++BBI;
423         EraseInstFromFunction(*PrevSI);
424         continue;
425       }
426       break;
427     }
428     
429     // If this is a load, we have to stop.  However, if the loaded value is from
430     // the pointer we're loading and is producing the pointer we're storing,
431     // then *this* store is dead (X = load P; store X -> P).
432     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
433       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
434           !SI.isVolatile())
435         return EraseInstFromFunction(SI);
436       
437       // Otherwise, this is a load from some other location.  Stores before it
438       // may not be dead.
439       break;
440     }
441     
442     // Don't skip over loads or things that can modify memory.
443     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
444       break;
445   }
446   
447   
448   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
449
450   // store X, null    -> turns into 'unreachable' in SimplifyCFG
451   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
452     if (!isa<UndefValue>(Val)) {
453       SI.setOperand(0, UndefValue::get(Val->getType()));
454       if (Instruction *U = dyn_cast<Instruction>(Val))
455         Worklist.Add(U);  // Dropped a use.
456     }
457     return 0;  // Do not modify these!
458   }
459
460   // store undef, Ptr -> noop
461   if (isa<UndefValue>(Val))
462     return EraseInstFromFunction(SI);
463
464   // If the pointer destination is a cast, see if we can fold the cast into the
465   // source instead.
466   if (isa<CastInst>(Ptr))
467     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
468       return Res;
469   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
470     if (CE->isCast())
471       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
472         return Res;
473
474   
475   // If this store is the last instruction in the basic block (possibly
476   // excepting debug info instructions), and if the block ends with an
477   // unconditional branch, try to move it to the successor block.
478   BBI = &SI; 
479   do {
480     ++BBI;
481   } while (isa<DbgInfoIntrinsic>(BBI) ||
482            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
483   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
484     if (BI->isUnconditional())
485       if (SimplifyStoreAtEndOfBlock(SI))
486         return 0;  // xform done!
487   
488   return 0;
489 }
490
491 /// SimplifyStoreAtEndOfBlock - Turn things like:
492 ///   if () { *P = v1; } else { *P = v2 }
493 /// into a phi node with a store in the successor.
494 ///
495 /// Simplify things like:
496 ///   *P = v1; if () { *P = v2; }
497 /// into a phi node with a store in the successor.
498 ///
499 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
500   BasicBlock *StoreBB = SI.getParent();
501   
502   // Check to see if the successor block has exactly two incoming edges.  If
503   // so, see if the other predecessor contains a store to the same location.
504   // if so, insert a PHI node (if needed) and move the stores down.
505   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
506   
507   // Determine whether Dest has exactly two predecessors and, if so, compute
508   // the other predecessor.
509   pred_iterator PI = pred_begin(DestBB);
510   BasicBlock *P = *PI;
511   BasicBlock *OtherBB = 0;
512
513   if (P != StoreBB)
514     OtherBB = P;
515
516   if (++PI == pred_end(DestBB))
517     return false;
518   
519   P = *PI;
520   if (P != StoreBB) {
521     if (OtherBB)
522       return false;
523     OtherBB = P;
524   }
525   if (++PI != pred_end(DestBB))
526     return false;
527
528   // Bail out if all the relevant blocks aren't distinct (this can happen,
529   // for example, if SI is in an infinite loop)
530   if (StoreBB == DestBB || OtherBB == DestBB)
531     return false;
532
533   // Verify that the other block ends in a branch and is not otherwise empty.
534   BasicBlock::iterator BBI = OtherBB->getTerminator();
535   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
536   if (!OtherBr || BBI == OtherBB->begin())
537     return false;
538   
539   // If the other block ends in an unconditional branch, check for the 'if then
540   // else' case.  there is an instruction before the branch.
541   StoreInst *OtherStore = 0;
542   if (OtherBr->isUnconditional()) {
543     --BBI;
544     // Skip over debugging info.
545     while (isa<DbgInfoIntrinsic>(BBI) ||
546            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
547       if (BBI==OtherBB->begin())
548         return false;
549       --BBI;
550     }
551     // If this isn't a store, isn't a store to the same location, or if the
552     // alignments differ, bail out.
553     OtherStore = dyn_cast<StoreInst>(BBI);
554     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
555         OtherStore->getAlignment() != SI.getAlignment())
556       return false;
557   } else {
558     // Otherwise, the other block ended with a conditional branch. If one of the
559     // destinations is StoreBB, then we have the if/then case.
560     if (OtherBr->getSuccessor(0) != StoreBB && 
561         OtherBr->getSuccessor(1) != StoreBB)
562       return false;
563     
564     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
565     // if/then triangle.  See if there is a store to the same ptr as SI that
566     // lives in OtherBB.
567     for (;; --BBI) {
568       // Check to see if we find the matching store.
569       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
570         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
571             OtherStore->getAlignment() != SI.getAlignment())
572           return false;
573         break;
574       }
575       // If we find something that may be using or overwriting the stored
576       // value, or if we run out of instructions, we can't do the xform.
577       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
578           BBI == OtherBB->begin())
579         return false;
580     }
581     
582     // In order to eliminate the store in OtherBr, we have to
583     // make sure nothing reads or overwrites the stored value in
584     // StoreBB.
585     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
586       // FIXME: This should really be AA driven.
587       if (I->mayReadFromMemory() || I->mayWriteToMemory())
588         return false;
589     }
590   }
591   
592   // Insert a PHI node now if we need it.
593   Value *MergedVal = OtherStore->getOperand(0);
594   if (MergedVal != SI.getOperand(0)) {
595     PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
596     PN->addIncoming(SI.getOperand(0), SI.getParent());
597     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
598     MergedVal = InsertNewInstBefore(PN, DestBB->front());
599   }
600   
601   // Advance to a place where it is safe to insert the new store and
602   // insert it.
603   BBI = DestBB->getFirstNonPHI();
604   StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
605                                    OtherStore->isVolatile(),
606                                    SI.getAlignment());
607   InsertNewInstBefore(NewSI, *BBI);
608   NewSI->setDebugLoc(OtherStore->getDebugLoc()); 
609
610   // Nuke the old stores.
611   EraseInstFromFunction(SI);
612   EraseInstFromFunction(*OtherStore);
613   return true;
614 }