1 //===- LevelRaise.cpp - Code to change LLVM to higher level ---------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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
14 //===----------------------------------------------------------------------===//
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"
29 // StartInst - This enables the -raise-start-inst=foo option to cause the level
30 // raising pass to start at instruction "foo", which is immensely useful for
33 static cl::opt<std::string>
34 StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
35 cl::desc("Start raise pass at the instruction with the specified name"));
38 NumLoadStorePeepholes("raise", "Number of load/store peepholes");
41 NumGEPInstFormed("raise", "Number of other getelementptr's formed");
44 NumExprTreesConv("raise", "Number of expression trees converted");
47 NumCastOfCast("raise", "Number of cast-of-self removed");
50 NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
53 NumVarargCallChanges("raise", "Number of vararg call peepholes");
55 #define PRINT_PEEPHOLE(ID, NUM, I) \
56 DOUT << "Inst P/H " << ID << "[" << NUM << "] " << I
58 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
59 #define PRINT_PEEPHOLE2(ID, I1, I2) \
60 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
61 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
62 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
63 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
64 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
65 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
66 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
69 struct RPR : public FunctionPass {
70 virtual bool runOnFunction(Function &F);
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.addRequired<TargetData>();
78 bool DoRaisePass(Function &F);
79 bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
82 RegisterPass<RPR> X("raise", "Raise Pointer References");
86 FunctionPass *llvm::createRaisePointerReferencesPass() {
91 // isReinterpretingCast - Return true if the cast instruction specified will
92 // cause the operand to be "reinterpreted". A value is reinterpreted if the
93 // cast instruction would cause the underlying bits to change.
95 static inline bool isReinterpretingCast(const CastInst *CI) {
96 return!CI->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI->getType());
99 bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
101 const TargetData &TD = getAnalysis<TargetData>();
103 if (CastInst *CI = dyn_cast<CastInst>(I)) {
104 Value *Src = CI->getOperand(0);
105 const Type *DestTy = CI->getType();
107 // Peephole optimize the following instruction:
108 // %V2 = cast <ty> %V to <ty>
112 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
113 PRINT_PEEPHOLE1("cast-of-self-ty", *CI);
114 CI->replaceAllUsesWith(Src);
115 if (!Src->hasName() && CI->hasName()) {
116 std::string Name = CI->getName();
121 // DCE the instruction now, to avoid having the iterative version of DCE
122 // have to worry about it.
124 BI = BB->getInstList().erase(BI);
130 // Check to see if it's a cast of an instruction that does not depend on the
131 // specific type of the operands to do it's job.
132 if (!isReinterpretingCast(CI)) {
133 ValueTypeCache ConvertedTypes;
135 // Check to see if we can convert the source of the cast to match the
136 // destination type of the cast...
138 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
139 if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
140 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", *Src, *CI, *BB->getParent());
142 DOUT << "\nCONVERTING SRC EXPR TYPE:\n";
143 { // ValueMap must be destroyed before function verified!
144 ValueMapCache ValueMap;
145 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
147 if (Constant *CPV = dyn_cast<Constant>(E))
148 CI->replaceAllUsesWith(CPV);
150 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", *E);
151 DOUT << "DONE CONVERTING SRC EXPR TYPE: \n"
155 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
160 // Check to see if we can convert the users of the cast value to match the
161 // source type of the cast...
163 ConvertedTypes.clear();
164 // Make sure the source doesn't change type
165 ConvertedTypes[Src] = Src->getType();
166 if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
167 //PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", *Src, *CI,
168 // *BB->getParent());
170 DOUT << "\nCONVERTING EXPR TYPE:\n";
171 { // ValueMap must be destroyed before function verified!
172 ValueMapCache ValueMap;
173 ConvertValueToNewType(CI, Src, ValueMap, TD); // This will delete CI!
176 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", *Src);
177 DOUT << "DONE CONVERTING EXPR TYPE: \n\n" << *BB->getParent();
179 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
185 // Check to see if we are casting from a structure pointer to a pointer to
186 // the first element of the structure... to avoid munching other peepholes,
187 // we only let this happen if there are no add uses of the cast.
189 // Peephole optimize the following instructions:
190 // %t1 = cast {<...>} * %StructPtr to <ty> *
192 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
193 // %t1 = cast <eltype> * %t1 to <ty> *
195 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
196 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
198 // Loop over uses of the cast, checking for add instructions. If an add
199 // exists, this is probably a part of a more complex GEP, so we don't
200 // want to mess around with the cast.
202 bool HasAddUse = false;
203 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
205 if (isa<Instruction>(*I) &&
206 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
207 HasAddUse = true; break;
210 // If it doesn't have an add use, check to see if the dest type is
211 // losslessly convertible to one of the types in the start of the struct
215 const Type *DestPointedTy = DestPTy->getElementType();
217 const CompositeType *CurCTy = CTy;
218 const Type *ElTy = 0;
220 // Build the index vector, full of all zeros
221 std::vector<Value*> Indices;
223 Indices.push_back(Constant::getNullValue(Type::UIntTy));
224 while (CurCTy && !isa<PointerType>(CurCTy)) {
225 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
226 // Check for a zero element struct type... if we have one, bail.
227 if (CurSTy->getNumElements() == 0) break;
229 // Grab the first element of the struct type, which must lie at
230 // offset zero in the struct.
232 ElTy = CurSTy->getElementType(0);
234 ElTy = cast<SequentialType>(CurCTy)->getElementType();
237 // Insert a zero to index through this type...
238 Indices.push_back(Constant::getNullValue(Type::UIntTy));
240 // Did we find what we're looking for?
241 if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
243 // Nope, go a level deeper.
245 CurCTy = dyn_cast<CompositeType>(ElTy);
249 // Did we find what we were looking for? If so, do the transformation
251 PRINT_PEEPHOLE1("cast-for-first:in", *CI);
253 std::string Name = CI->getName(); CI->setName("");
255 // Insert the new T cast instruction... stealing old T's name
256 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
259 // Make the old cast instruction reference the new GEP instead of
260 // the old src value.
262 CI->setOperand(0, GEP);
264 PRINT_PEEPHOLE2("cast-for-first:out", *GEP, *CI);
271 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
272 Value *Val = SI->getOperand(0);
273 Value *Pointer = SI->getPointerOperand();
275 // Peephole optimize the following instructions:
276 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
277 // store <T2> %V, <T2>* %t
280 // %t = cast <T2> %V to <T1>
281 // store <T1> %t2, <T1>* %P
283 // Note: This is not taken care of by expr conversion because there might
284 // not be a cast available for the store to convert the incoming value of.
285 // This code is basically here to make sure that pointers don't have casts
288 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
289 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
290 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
291 // convertible types?
292 if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
293 PRINT_PEEPHOLE3("st-src-cast:in ", *Pointer, *Val, *SI);
295 // Insert the new T cast instruction... stealing old T's name
296 std::string Name(CI->getName()); CI->setName("");
297 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
300 // Replace the old store with a new one!
301 ReplaceInstWithInst(BB->getInstList(), BI,
302 SI = new StoreInst(NCI, CastSrc));
303 PRINT_PEEPHOLE3("st-src-cast:out", *NCI, *CastSrc, *SI);
304 ++NumLoadStorePeepholes;
308 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
309 Value *Pointer = LI->getOperand(0);
310 const Type *PtrElType =
311 cast<PointerType>(Pointer->getType())->getElementType();
313 // Peephole optimize the following instructions:
314 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertible to T2
315 // %t = load <T2>* %P
318 // %t = load <T1>* %P
319 // %Val = cast <T1> to <T2>
321 // Note: This is not taken care of by expr conversion because there might
322 // not be a cast available for the store to convert the incoming value of.
323 // This code is basically here to make sure that pointers don't have casts
326 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
327 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
328 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
329 // convertible types?
330 if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
331 PRINT_PEEPHOLE2("load-src-cast:in ", *Pointer, *LI);
333 // Create the new load instruction... loading the pre-casted value
334 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
336 // Insert the new T cast instruction... stealing old T's name
337 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
339 // Replace the old store with a new one!
340 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
341 PRINT_PEEPHOLE3("load-src-cast:out", *NCI, *CastSrc, *NewLI);
342 ++NumLoadStorePeepholes;
346 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
347 // If we have a call with all varargs arguments, convert the call to use the
348 // actual argument types present...
350 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
351 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
353 // Is the call to a vararg variable with no real parameters?
354 if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
355 !CI->getCalledFunction()) {
356 // If so, insert a new cast instruction, casting it to a function type
357 // that matches the current arguments...
359 std::vector<const Type *> Params; // Parameter types...
360 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
361 Params.push_back(CI->getOperand(i)->getType());
363 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
365 PointerType *NewPFunTy = PointerType::get(NewFT);
367 // Create a new cast, inserting it right before the function call...
369 Constant *ConstantCallSrc = 0;
370 if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
371 ConstantCallSrc = CS;
374 NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
376 NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
377 CI->getCalledValue()->getName()+"_c",CI);
379 // Create a new call instruction...
380 CallInst *NewCall = new CallInst(NewCast,
381 std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
382 if (CI->isTailCall()) NewCall->setTailCall();
383 NewCall->setCallingConv(CI->getCallingConv());
385 ReplaceInstWithInst(CI, NewCall);
387 ++NumVarargCallChanges;
399 bool RPR::DoRaisePass(Function &F) {
400 bool Changed = false;
401 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
402 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
403 DOUT << "LevelRaising: " << *BI;
404 if (dceInstruction(BI) || doConstantPropagation(BI)) {
407 DOUT << "***\t\t^^-- Dead code eliminated!\n";
408 } else if (PeepholeOptimize(BB, BI)) {
419 // runOnFunction - Raise a function representation to a higher level.
420 bool RPR::runOnFunction(Function &F) {
421 DOUT << "\n\n\nStarting to work on Function '" << F.getName() << "'\n";
423 // Insert casts for all incoming pointer pointer values that are treated as
426 bool Changed = false, LocalChange;
428 // If the StartInst option was specified, then Peephole optimize that
429 // instruction first if it occurs in this function.
431 if (!StartInst.empty()) {
432 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
433 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
434 if (BI->getName() == StartInst) {
435 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
436 DebugFlag = true; // Turn on DEBUG's
437 Changed |= PeepholeOptimize(BB, BI);
438 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
443 DOUT << "Looping: \n" << F;
445 // Iterate over the function, refining it, until it converges on a stable
448 while (DoRaisePass(F)) LocalChange = true;
449 Changed |= LocalChange;
451 } while (LocalChange);