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"
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
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"));
39 NumLoadStorePeepholes("raise", "Number of load/store peepholes");
42 NumGEPInstFormed("raise", "Number of other getelementptr's formed");
45 NumExprTreesConv("raise", "Number of expression trees converted");
48 NumCastOfCast("raise", "Number of cast-of-self removed");
51 NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
54 NumVarargCallChanges("raise", "Number of vararg call peepholes");
56 #define PRINT_PEEPHOLE(ID, NUM, I) \
57 DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
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)
70 struct RPR : public FunctionPass {
71 virtual bool runOnFunction(Function &F);
73 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addRequired<TargetData>();
79 bool DoRaisePass(Function &F);
80 bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
83 RegisterOpt<RPR> X("raise", "Raise Pointer References");
87 FunctionPass *llvm::createRaisePointerReferencesPass() {
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.
96 static inline bool isReinterpretingCast(const CastInst *CI) {
97 return!CI->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI->getType());
100 bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
102 const TargetData &TD = getAnalysis<TargetData>();
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();
109 // Peephole optimize the following instruction:
110 // %V2 = cast <ty> %V to <ty>
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();
123 // DCE the instruction now, to avoid having the iterative version of DCE
124 // have to worry about it.
126 BI = BB->getInstList().erase(BI);
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;
137 // Check to see if we can convert the source of the cast to match the
138 // destination type of the cast...
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());
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);
149 if (Constant *CPV = dyn_cast<Constant>(E))
150 CI->replaceAllUsesWith(CPV);
152 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", *E);
153 DEBUG(std::cerr << "DONE CONVERTING SRC EXPR TYPE: \n"
154 << *BB->getParent());
157 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
162 // Check to see if we can convert the users of the cast value to match the
163 // source type of the cast...
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());
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!
178 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", *Src);
179 DEBUG(std::cerr << "DONE CONVERTING EXPR TYPE: \n\n" <<
182 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
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.
192 // Peephole optimize the following instructions:
193 // %t1 = cast {<...>} * %StructPtr to <ty> *
195 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
196 // %t1 = cast <eltype> * %t1 to <ty> *
198 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
199 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
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.
205 bool HasAddUse = false;
206 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
208 if (isa<Instruction>(*I) &&
209 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
210 HasAddUse = true; break;
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
218 const Type *DestPointedTy = DestPTy->getElementType();
220 const CompositeType *CurCTy = CTy;
221 const Type *ElTy = 0;
223 // Build the index vector, full of all zeros
224 std::vector<Value*> Indices;
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;
232 // Grab the first element of the struct type, which must lie at
233 // offset zero in the struct.
235 ElTy = CurSTy->getElementType(0);
237 ElTy = cast<SequentialType>(CurCTy)->getElementType();
240 // Insert a zero to index through this type...
241 Indices.push_back(Constant::getNullValue(Type::UIntTy));
243 // Did we find what we're looking for?
244 if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
246 // Nope, go a level deeper.
248 CurCTy = dyn_cast<CompositeType>(ElTy);
252 // Did we find what we were looking for? If so, do the transformation
254 PRINT_PEEPHOLE1("cast-for-first:in", *CI);
256 std::string Name = CI->getName(); CI->setName("");
258 // Insert the new T cast instruction... stealing old T's name
259 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
262 // Make the old cast instruction reference the new GEP instead of
263 // the old src value.
265 CI->setOperand(0, GEP);
267 PRINT_PEEPHOLE2("cast-for-first:out", *GEP, *CI);
274 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
275 Value *Val = SI->getOperand(0);
276 Value *Pointer = SI->getPointerOperand();
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
283 // %t = cast <T2> %V to <T1>
284 // store <T1> %t2, <T1>* %P
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
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);
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(),
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;
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();
316 // Peephole optimize the following instructions:
317 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertible to T2
318 // %t = load <T2>* %P
321 // %t = load <T1>* %P
322 // %Val = cast <T1> to <T2>
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
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);
336 // Create the new load instruction... loading the pre-casted value
337 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
339 // Insert the new T cast instruction... stealing old T's name
340 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
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;
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...
353 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
354 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
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...
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());
366 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
368 PointerType *NewPFunTy = PointerType::get(NewFT);
370 // Create a new cast, inserting it right before the function call...
372 Constant *ConstantCallSrc = 0;
373 if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
374 ConstantCallSrc = CS;
377 NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
379 NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
380 CI->getCalledValue()->getName()+"_c",CI);
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());
388 ReplaceInstWithInst(CI, NewCall);
390 ++NumVarargCallChanges;
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)) {
410 DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
411 } else if (PeepholeOptimize(BB, BI)) {
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()
427 // Insert casts for all incoming pointer pointer values that are treated as
430 bool Changed = false, LocalChange;
432 // If the StartInst option was specified, then Peephole optimize that
433 // instruction first if it occurs in this function.
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
447 DEBUG(std::cerr << "Looping: \n" << F);
449 // Iterate over the function, refining it, until it converges on a stable
452 while (DoRaisePass(F)) LocalChange = true;
453 Changed |= LocalChange;
455 } while (LocalChange);