Added separate alias instructions for SSE logical ops that operate on non-packed...
[oota-llvm.git] / lib / Transforms / LevelRaise.cpp
1 //===- LevelRaise.cpp - Code to change LLVM to higher level ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the 'raising' part of the LevelChange API.  This is
11 // useful because, in general, it makes the LLVM code terser and easier to
12 // analyze.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Transforms/Utils/Local.h"
18 #include "TransformInternals.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include <algorithm>
27 #include <iostream>
28 using namespace llvm;
29
30 // StartInst - This enables the -raise-start-inst=foo option to cause the level
31 // raising pass to start at instruction "foo", which is immensely useful for
32 // debugging!
33 //
34 static cl::opt<std::string>
35 StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
36        cl::desc("Start raise pass at the instruction with the specified name"));
37
38 static Statistic<>
39 NumLoadStorePeepholes("raise", "Number of load/store peepholes");
40
41 static Statistic<>
42 NumGEPInstFormed("raise", "Number of other getelementptr's formed");
43
44 static Statistic<>
45 NumExprTreesConv("raise", "Number of expression trees converted");
46
47 static Statistic<>
48 NumCastOfCast("raise", "Number of cast-of-self removed");
49
50 static Statistic<>
51 NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
52
53 static Statistic<>
54 NumVarargCallChanges("raise", "Number of vararg call peepholes");
55
56 #define PRINT_PEEPHOLE(ID, NUM, I)            \
57   DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
58
59 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
60 #define PRINT_PEEPHOLE2(ID, I1, I2) \
61   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
62 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
63   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
64        PRINT_PEEPHOLE(ID, 2, I3); } while (0)
65 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
66   do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
67        PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
68
69 namespace {
70   struct RPR : public FunctionPass {
71     virtual bool runOnFunction(Function &F);
72
73     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
74       AU.setPreservesCFG();
75       AU.addRequired<TargetData>();
76     }
77
78   private:
79     bool DoRaisePass(Function &F);
80     bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
81   };
82
83   RegisterOpt<RPR> X("raise", "Raise Pointer References");
84 }
85
86
87 FunctionPass *llvm::createRaisePointerReferencesPass() {
88   return new RPR();
89 }
90
91
92 // isReinterpretingCast - Return true if the cast instruction specified will
93 // cause the operand to be "reinterpreted".  A value is reinterpreted if the
94 // cast instruction would cause the underlying bits to change.
95 //
96 static inline bool isReinterpretingCast(const CastInst *CI) {
97   return!CI->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI->getType());
98 }
99
100 bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
101   Instruction *I = BI;
102   const TargetData &TD = getAnalysis<TargetData>();
103
104   if (CastInst *CI = dyn_cast<CastInst>(I)) {
105     Value       *Src    = CI->getOperand(0);
106     Instruction *SrcI   = dyn_cast<Instruction>(Src); // Nonnull if instr source
107     const Type  *DestTy = CI->getType();
108
109     // Peephole optimize the following instruction:
110     // %V2 = cast <ty> %V to <ty>
111     //
112     // Into: <nothing>
113     //
114     if (DestTy == Src->getType()) {   // Check for a cast to same type as src!!
115       PRINT_PEEPHOLE1("cast-of-self-ty", *CI);
116       CI->replaceAllUsesWith(Src);
117       if (!Src->hasName() && CI->hasName()) {
118         std::string Name = CI->getName();
119         CI->setName("");
120         Src->setName(Name);
121       }
122
123       // DCE the instruction now, to avoid having the iterative version of DCE
124       // have to worry about it.
125       //
126       BI = BB->getInstList().erase(BI);
127
128       ++NumCastOfCast;
129       return true;
130     }
131
132     // Check to see if it's a cast of an instruction that does not depend on the
133     // specific type of the operands to do it's job.
134     if (!isReinterpretingCast(CI)) {
135       ValueTypeCache ConvertedTypes;
136
137       // Check to see if we can convert the source of the cast to match the
138       // destination type of the cast...
139       //
140       ConvertedTypes[CI] = CI->getType();  // Make sure the cast doesn't change
141       if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
142         PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", *Src, *CI, *BB->getParent());
143
144         DEBUG(std::cerr << "\nCONVERTING SRC EXPR TYPE:\n");
145         { // ValueMap must be destroyed before function verified!
146           ValueMapCache ValueMap;
147           Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
148
149           if (Constant *CPV = dyn_cast<Constant>(E))
150             CI->replaceAllUsesWith(CPV);
151
152           PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", *E);
153           DEBUG(std::cerr << "DONE CONVERTING SRC EXPR TYPE: \n"
154                           << *BB->getParent());
155         }
156
157         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
158         ++NumExprTreesConv;
159         return true;
160       }
161
162       // Check to see if we can convert the users of the cast value to match the
163       // source type of the cast...
164       //
165       ConvertedTypes.clear();
166       // Make sure the source doesn't change type
167       ConvertedTypes[Src] = Src->getType();
168       if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
169         //PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", *Src, *CI,
170         //                *BB->getParent());
171
172         DEBUG(std::cerr << "\nCONVERTING EXPR TYPE:\n");
173         { // ValueMap must be destroyed before function verified!
174           ValueMapCache ValueMap;
175           ConvertValueToNewType(CI, Src, ValueMap, TD);  // This will delete CI!
176         }
177
178         PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", *Src);
179         DEBUG(std::cerr << "DONE CONVERTING EXPR TYPE: \n\n" <<
180               *BB->getParent());
181
182         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
183         ++NumExprTreesConv;
184         return true;
185       }
186     }
187
188     // Check to see if we are casting from a structure pointer to a pointer to
189     // the first element of the structure... to avoid munching other peepholes,
190     // we only let this happen if there are no add uses of the cast.
191     //
192     // Peephole optimize the following instructions:
193     // %t1 = cast {<...>} * %StructPtr to <ty> *
194     //
195     // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
196     //       %t1 = cast <eltype> * %t1 to <ty> *
197     //
198     if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
199       if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
200
201         // Loop over uses of the cast, checking for add instructions.  If an add
202         // exists, this is probably a part of a more complex GEP, so we don't
203         // want to mess around with the cast.
204         //
205         bool HasAddUse = false;
206         for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
207              I != E; ++I)
208           if (isa<Instruction>(*I) &&
209               cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
210             HasAddUse = true; break;
211           }
212
213         // If it doesn't have an add use, check to see if the dest type is
214         // losslessly convertible to one of the types in the start of the struct
215         // type.
216         //
217         if (!HasAddUse) {
218           const Type *DestPointedTy = DestPTy->getElementType();
219           unsigned Depth = 1;
220           const CompositeType *CurCTy = CTy;
221           const Type *ElTy = 0;
222
223           // Build the index vector, full of all zeros
224           std::vector<Value*> Indices;
225
226           Indices.push_back(Constant::getNullValue(Type::UIntTy));
227           while (CurCTy && !isa<PointerType>(CurCTy)) {
228             if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
229               // Check for a zero element struct type... if we have one, bail.
230               if (CurSTy->getNumElements() == 0) break;
231
232               // Grab the first element of the struct type, which must lie at
233               // offset zero in the struct.
234               //
235               ElTy = CurSTy->getElementType(0);
236             } else {
237               ElTy = cast<SequentialType>(CurCTy)->getElementType();
238             }
239
240             // Insert a zero to index through this type...
241             Indices.push_back(Constant::getNullValue(Type::UIntTy));
242
243             // Did we find what we're looking for?
244             if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
245
246             // Nope, go a level deeper.
247             ++Depth;
248             CurCTy = dyn_cast<CompositeType>(ElTy);
249             ElTy = 0;
250           }
251
252           // Did we find what we were looking for? If so, do the transformation
253           if (ElTy) {
254             PRINT_PEEPHOLE1("cast-for-first:in", *CI);
255
256             std::string Name = CI->getName(); CI->setName("");
257
258             // Insert the new T cast instruction... stealing old T's name
259             GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
260                                                            Name, BI);
261
262             // Make the old cast instruction reference the new GEP instead of
263             // the old src value.
264             //
265             CI->setOperand(0, GEP);
266
267             PRINT_PEEPHOLE2("cast-for-first:out", *GEP, *CI);
268             ++NumGEPInstFormed;
269             return true;
270           }
271         }
272       }
273
274   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
275     Value *Val     = SI->getOperand(0);
276     Value *Pointer = SI->getPointerOperand();
277
278     // Peephole optimize the following instructions:
279     // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
280     // store <T2> %V, <T2>* %t
281     //
282     // Into:
283     // %t = cast <T2> %V to <T1>
284     // store <T1> %t2, <T1>* %P
285     //
286     // Note: This is not taken care of by expr conversion because there might
287     // not be a cast available for the store to convert the incoming value of.
288     // This code is basically here to make sure that pointers don't have casts
289     // if possible.
290     //
291     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
292       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
293         if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
294           // convertible types?
295           if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
296             PRINT_PEEPHOLE3("st-src-cast:in ", *Pointer, *Val, *SI);
297
298             // Insert the new T cast instruction... stealing old T's name
299             std::string Name(CI->getName()); CI->setName("");
300             CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
301                                          Name, BI);
302
303             // Replace the old store with a new one!
304             ReplaceInstWithInst(BB->getInstList(), BI,
305                                 SI = new StoreInst(NCI, CastSrc));
306             PRINT_PEEPHOLE3("st-src-cast:out", *NCI, *CastSrc, *SI);
307             ++NumLoadStorePeepholes;
308             return true;
309           }
310
311   } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
312     Value *Pointer = LI->getOperand(0);
313     const Type *PtrElType =
314       cast<PointerType>(Pointer->getType())->getElementType();
315
316     // Peephole optimize the following instructions:
317     // %Val = cast <T1>* to <T2>*    ;; If T1 is losslessly convertible to T2
318     // %t = load <T2>* %P
319     //
320     // Into:
321     // %t = load <T1>* %P
322     // %Val = cast <T1> to <T2>
323     //
324     // Note: This is not taken care of by expr conversion because there might
325     // not be a cast available for the store to convert the incoming value of.
326     // This code is basically here to make sure that pointers don't have casts
327     // if possible.
328     //
329     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
330       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
331         if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
332           // convertible types?
333           if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
334             PRINT_PEEPHOLE2("load-src-cast:in ", *Pointer, *LI);
335
336             // Create the new load instruction... loading the pre-casted value
337             LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
338
339             // Insert the new T cast instruction... stealing old T's name
340             CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
341
342             // Replace the old store with a new one!
343             ReplaceInstWithInst(BB->getInstList(), BI, NCI);
344             PRINT_PEEPHOLE3("load-src-cast:out", *NCI, *CastSrc, *NewLI);
345             ++NumLoadStorePeepholes;
346             return true;
347           }
348
349   } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
350     // If we have a call with all varargs arguments, convert the call to use the
351     // actual argument types present...
352     //
353     const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
354     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
355
356     // Is the call to a vararg variable with no real parameters?
357     if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
358         !CI->getCalledFunction()) {
359       // If so, insert a new cast instruction, casting it to a function type
360       // that matches the current arguments...
361       //
362       std::vector<const Type *> Params;  // Parameter types...
363       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
364         Params.push_back(CI->getOperand(i)->getType());
365
366       FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
367                                               Params, false);
368       PointerType *NewPFunTy = PointerType::get(NewFT);
369
370       // Create a new cast, inserting it right before the function call...
371       Value *NewCast;
372       Constant *ConstantCallSrc = 0;
373       if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
374         ConstantCallSrc = CS;
375
376       if (ConstantCallSrc)
377         NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
378       else
379         NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
380                                CI->getCalledValue()->getName()+"_c",CI);
381
382       // Create a new call instruction...
383       CallInst *NewCall = new CallInst(NewCast,
384                            std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
385       if (CI->isTailCall()) NewCall->setTailCall();
386       NewCall->setCallingConv(CI->getCallingConv());
387       ++BI;
388       ReplaceInstWithInst(CI, NewCall);
389
390       ++NumVarargCallChanges;
391       return true;
392     }
393
394   }
395
396   return false;
397 }
398
399
400
401
402 bool RPR::DoRaisePass(Function &F) {
403   bool Changed = false;
404   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
405     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
406       DEBUG(std::cerr << "LevelRaising: " << *BI);
407       if (dceInstruction(BI) || doConstantPropagation(BI)) {
408         Changed = true;
409         ++NumDCEorCP;
410         DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
411       } else if (PeepholeOptimize(BB, BI)) {
412         Changed = true;
413       } else {
414         ++BI;
415       }
416     }
417
418   return Changed;
419 }
420
421
422 // runOnFunction - Raise a function representation to a higher level.
423 bool RPR::runOnFunction(Function &F) {
424   DEBUG(std::cerr << "\n\n\nStarting to work on Function '" << F.getName()
425                   << "'\n");
426
427   // Insert casts for all incoming pointer pointer values that are treated as
428   // arrays...
429   //
430   bool Changed = false, LocalChange;
431
432   // If the StartInst option was specified, then Peephole optimize that
433   // instruction first if it occurs in this function.
434   //
435   if (!StartInst.empty()) {
436     for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
437       for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
438         if (BI->getName() == StartInst) {
439           bool SavedDebug = DebugFlag;  // Save the DEBUG() controlling flag.
440           DebugFlag = true;             // Turn on DEBUG's
441           Changed |= PeepholeOptimize(BB, BI);
442           DebugFlag = SavedDebug;       // Restore DebugFlag to previous state
443         }
444   }
445
446   do {
447     DEBUG(std::cerr << "Looping: \n" << F);
448
449     // Iterate over the function, refining it, until it converges on a stable
450     // state
451     LocalChange = false;
452     while (DoRaisePass(F)) LocalChange = true;
453     Changed |= LocalChange;
454
455   } while (LocalChange);
456
457   return Changed;
458 }
459