s|llvm/Support/Visibility.h|llvm/Support/Compiler.h|
[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     const Type  *DestTy = CI->getType();
107
108     // Peephole optimize the following instruction:
109     // %V2 = cast <ty> %V to <ty>
110     //
111     // Into: <nothing>
112     //
113     if (DestTy == Src->getType()) {   // Check for a cast to same type as src!!
114       PRINT_PEEPHOLE1("cast-of-self-ty", *CI);
115       CI->replaceAllUsesWith(Src);
116       if (!Src->hasName() && CI->hasName()) {
117         std::string Name = CI->getName();
118         CI->setName("");
119         Src->setName(Name);
120       }
121
122       // DCE the instruction now, to avoid having the iterative version of DCE
123       // have to worry about it.
124       //
125       BI = BB->getInstList().erase(BI);
126
127       ++NumCastOfCast;
128       return true;
129     }
130
131     // Check to see if it's a cast of an instruction that does not depend on the
132     // specific type of the operands to do it's job.
133     if (!isReinterpretingCast(CI)) {
134       ValueTypeCache ConvertedTypes;
135
136       // Check to see if we can convert the source of the cast to match the
137       // destination type of the cast...
138       //
139       ConvertedTypes[CI] = CI->getType();  // Make sure the cast doesn't change
140       if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
141         PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", *Src, *CI, *BB->getParent());
142
143         DEBUG(std::cerr << "\nCONVERTING SRC EXPR TYPE:\n");
144         { // ValueMap must be destroyed before function verified!
145           ValueMapCache ValueMap;
146           Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
147
148           if (Constant *CPV = dyn_cast<Constant>(E))
149             CI->replaceAllUsesWith(CPV);
150
151           PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", *E);
152           DEBUG(std::cerr << "DONE CONVERTING SRC EXPR TYPE: \n"
153                           << *BB->getParent());
154         }
155
156         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
157         ++NumExprTreesConv;
158         return true;
159       }
160
161       // Check to see if we can convert the users of the cast value to match the
162       // source type of the cast...
163       //
164       ConvertedTypes.clear();
165       // Make sure the source doesn't change type
166       ConvertedTypes[Src] = Src->getType();
167       if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
168         //PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", *Src, *CI,
169         //                *BB->getParent());
170
171         DEBUG(std::cerr << "\nCONVERTING EXPR TYPE:\n");
172         { // ValueMap must be destroyed before function verified!
173           ValueMapCache ValueMap;
174           ConvertValueToNewType(CI, Src, ValueMap, TD);  // This will delete CI!
175         }
176
177         PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", *Src);
178         DEBUG(std::cerr << "DONE CONVERTING EXPR TYPE: \n\n" <<
179               *BB->getParent());
180
181         BI = BB->begin();  // Rescan basic block.  BI might be invalidated.
182         ++NumExprTreesConv;
183         return true;
184       }
185     }
186
187     // Check to see if we are casting from a structure pointer to a pointer to
188     // the first element of the structure... to avoid munching other peepholes,
189     // we only let this happen if there are no add uses of the cast.
190     //
191     // Peephole optimize the following instructions:
192     // %t1 = cast {<...>} * %StructPtr to <ty> *
193     //
194     // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
195     //       %t1 = cast <eltype> * %t1 to <ty> *
196     //
197     if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
198       if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
199
200         // Loop over uses of the cast, checking for add instructions.  If an add
201         // exists, this is probably a part of a more complex GEP, so we don't
202         // want to mess around with the cast.
203         //
204         bool HasAddUse = false;
205         for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
206              I != E; ++I)
207           if (isa<Instruction>(*I) &&
208               cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
209             HasAddUse = true; break;
210           }
211
212         // If it doesn't have an add use, check to see if the dest type is
213         // losslessly convertible to one of the types in the start of the struct
214         // type.
215         //
216         if (!HasAddUse) {
217           const Type *DestPointedTy = DestPTy->getElementType();
218           unsigned Depth = 1;
219           const CompositeType *CurCTy = CTy;
220           const Type *ElTy = 0;
221
222           // Build the index vector, full of all zeros
223           std::vector<Value*> Indices;
224
225           Indices.push_back(Constant::getNullValue(Type::UIntTy));
226           while (CurCTy && !isa<PointerType>(CurCTy)) {
227             if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
228               // Check for a zero element struct type... if we have one, bail.
229               if (CurSTy->getNumElements() == 0) break;
230
231               // Grab the first element of the struct type, which must lie at
232               // offset zero in the struct.
233               //
234               ElTy = CurSTy->getElementType(0);
235             } else {
236               ElTy = cast<SequentialType>(CurCTy)->getElementType();
237             }
238
239             // Insert a zero to index through this type...
240             Indices.push_back(Constant::getNullValue(Type::UIntTy));
241
242             // Did we find what we're looking for?
243             if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
244
245             // Nope, go a level deeper.
246             ++Depth;
247             CurCTy = dyn_cast<CompositeType>(ElTy);
248             ElTy = 0;
249           }
250
251           // Did we find what we were looking for? If so, do the transformation
252           if (ElTy) {
253             PRINT_PEEPHOLE1("cast-for-first:in", *CI);
254
255             std::string Name = CI->getName(); CI->setName("");
256
257             // Insert the new T cast instruction... stealing old T's name
258             GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
259                                                            Name, BI);
260
261             // Make the old cast instruction reference the new GEP instead of
262             // the old src value.
263             //
264             CI->setOperand(0, GEP);
265
266             PRINT_PEEPHOLE2("cast-for-first:out", *GEP, *CI);
267             ++NumGEPInstFormed;
268             return true;
269           }
270         }
271       }
272
273   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
274     Value *Val     = SI->getOperand(0);
275     Value *Pointer = SI->getPointerOperand();
276
277     // Peephole optimize the following instructions:
278     // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
279     // store <T2> %V, <T2>* %t
280     //
281     // Into:
282     // %t = cast <T2> %V to <T1>
283     // store <T1> %t2, <T1>* %P
284     //
285     // Note: This is not taken care of by expr conversion because there might
286     // not be a cast available for the store to convert the incoming value of.
287     // This code is basically here to make sure that pointers don't have casts
288     // if possible.
289     //
290     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
291       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
292         if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
293           // convertible types?
294           if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
295             PRINT_PEEPHOLE3("st-src-cast:in ", *Pointer, *Val, *SI);
296
297             // Insert the new T cast instruction... stealing old T's name
298             std::string Name(CI->getName()); CI->setName("");
299             CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
300                                          Name, BI);
301
302             // Replace the old store with a new one!
303             ReplaceInstWithInst(BB->getInstList(), BI,
304                                 SI = new StoreInst(NCI, CastSrc));
305             PRINT_PEEPHOLE3("st-src-cast:out", *NCI, *CastSrc, *SI);
306             ++NumLoadStorePeepholes;
307             return true;
308           }
309
310   } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
311     Value *Pointer = LI->getOperand(0);
312     const Type *PtrElType =
313       cast<PointerType>(Pointer->getType())->getElementType();
314
315     // Peephole optimize the following instructions:
316     // %Val = cast <T1>* to <T2>*    ;; If T1 is losslessly convertible to T2
317     // %t = load <T2>* %P
318     //
319     // Into:
320     // %t = load <T1>* %P
321     // %Val = cast <T1> to <T2>
322     //
323     // Note: This is not taken care of by expr conversion because there might
324     // not be a cast available for the store to convert the incoming value of.
325     // This code is basically here to make sure that pointers don't have casts
326     // if possible.
327     //
328     if (CastInst *CI = dyn_cast<CastInst>(Pointer))
329       if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
330         if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
331           // convertible types?
332           if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
333             PRINT_PEEPHOLE2("load-src-cast:in ", *Pointer, *LI);
334
335             // Create the new load instruction... loading the pre-casted value
336             LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
337
338             // Insert the new T cast instruction... stealing old T's name
339             CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
340
341             // Replace the old store with a new one!
342             ReplaceInstWithInst(BB->getInstList(), BI, NCI);
343             PRINT_PEEPHOLE3("load-src-cast:out", *NCI, *CastSrc, *NewLI);
344             ++NumLoadStorePeepholes;
345             return true;
346           }
347
348   } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
349     // If we have a call with all varargs arguments, convert the call to use the
350     // actual argument types present...
351     //
352     const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
353     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
354
355     // Is the call to a vararg variable with no real parameters?
356     if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
357         !CI->getCalledFunction()) {
358       // If so, insert a new cast instruction, casting it to a function type
359       // that matches the current arguments...
360       //
361       std::vector<const Type *> Params;  // Parameter types...
362       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
363         Params.push_back(CI->getOperand(i)->getType());
364
365       FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
366                                               Params, false);
367       PointerType *NewPFunTy = PointerType::get(NewFT);
368
369       // Create a new cast, inserting it right before the function call...
370       Value *NewCast;
371       Constant *ConstantCallSrc = 0;
372       if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
373         ConstantCallSrc = CS;
374
375       if (ConstantCallSrc)
376         NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
377       else
378         NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
379                                CI->getCalledValue()->getName()+"_c",CI);
380
381       // Create a new call instruction...
382       CallInst *NewCall = new CallInst(NewCast,
383                            std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
384       if (CI->isTailCall()) NewCall->setTailCall();
385       NewCall->setCallingConv(CI->getCallingConv());
386       ++BI;
387       ReplaceInstWithInst(CI, NewCall);
388
389       ++NumVarargCallChanges;
390       return true;
391     }
392
393   }
394
395   return false;
396 }
397
398
399
400
401 bool RPR::DoRaisePass(Function &F) {
402   bool Changed = false;
403   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
404     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
405       DEBUG(std::cerr << "LevelRaising: " << *BI);
406       if (dceInstruction(BI) || doConstantPropagation(BI)) {
407         Changed = true;
408         ++NumDCEorCP;
409         DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
410       } else if (PeepholeOptimize(BB, BI)) {
411         Changed = true;
412       } else {
413         ++BI;
414       }
415     }
416
417   return Changed;
418 }
419
420
421 // runOnFunction - Raise a function representation to a higher level.
422 bool RPR::runOnFunction(Function &F) {
423   DEBUG(std::cerr << "\n\n\nStarting to work on Function '" << F.getName()
424                   << "'\n");
425
426   // Insert casts for all incoming pointer pointer values that are treated as
427   // arrays...
428   //
429   bool Changed = false, LocalChange;
430
431   // If the StartInst option was specified, then Peephole optimize that
432   // instruction first if it occurs in this function.
433   //
434   if (!StartInst.empty()) {
435     for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
436       for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
437         if (BI->getName() == StartInst) {
438           bool SavedDebug = DebugFlag;  // Save the DEBUG() controlling flag.
439           DebugFlag = true;             // Turn on DEBUG's
440           Changed |= PeepholeOptimize(BB, BI);
441           DebugFlag = SavedDebug;       // Restore DebugFlag to previous state
442         }
443   }
444
445   do {
446     DEBUG(std::cerr << "Looping: \n" << F);
447
448     // Iterate over the function, refining it, until it converges on a stable
449     // state
450     LocalChange = false;
451     while (DoRaisePass(F)) LocalChange = true;
452     Changed |= LocalChange;
453
454   } while (LocalChange);
455
456   return Changed;
457 }
458