1 //===- LevelRaise.cpp - Code to change LLVM to higher level -----------------=//
3 // This file implements the 'raising' part of the LevelChange API. This is
4 // useful because, in general, it makes the LLVM code terser and easier to
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Transforms/LevelChange.h"
10 #include "llvm/Transforms/Utils/Local.h"
11 #include "TransformInternals.h"
12 #include "llvm/iOther.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/Pass.h"
15 #include "llvm/ConstantHandling.h"
16 #include "llvm/Analysis/Expressions.h"
17 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
18 #include "Support/STLExtras.h"
19 #include "Support/StatisticReporter.h"
23 static Statistic<> NumLoadStorePeepholes("raise\t\t- Number of load/store peepholes");
24 static Statistic<> NumGEPInstFormed("raise\t\t- Number of other getelementptr's formed");
25 static Statistic<> NumExprTreesConv("raise\t\t- Number of expression trees converted");
26 static Statistic<> NumCastOfCast("raise\t\t- Number of cast-of-self removed");
27 static Statistic<> NumDCEorCP("raise\t\t- Number of insts DCE'd or constprop'd");
30 #define PRINT_PEEPHOLE(ID, NUM, I) \
31 DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
33 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
34 #define PRINT_PEEPHOLE2(ID, I1, I2) \
35 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
36 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
37 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
38 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
39 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
40 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
41 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
44 // isReinterpretingCast - Return true if the cast instruction specified will
45 // cause the operand to be "reinterpreted". A value is reinterpreted if the
46 // cast instruction would cause the underlying bits to change.
48 static inline bool isReinterpretingCast(const CastInst *CI) {
49 return!CI->getOperand(0)->getType()->isLosslesslyConvertableTo(CI->getType());
53 // Peephole optimize the following instructions:
54 // %t1 = cast ? to x *
55 // %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
57 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
58 // %t2 = cast <eltype> * %t3 to {<...>}*
60 static bool HandleCastToPointer(BasicBlock::iterator BI,
61 const PointerType *DestPTy) {
62 CastInst &CI = cast<CastInst>(*BI);
63 if (CI.use_empty()) return false;
65 // Scan all of the uses, looking for any uses that are not add
66 // instructions. If we have non-adds, do not make this transformation.
68 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
70 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
71 if (BO->getOpcode() != Instruction::Add)
78 std::vector<Value*> Indices;
79 Value *Src = CI.getOperand(0);
80 const Type *Result = ConvertableToGEP(DestPTy, Src, Indices, &BI);
81 if (Result == 0) return false; // Not convertable...
83 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
85 // If we have a getelementptr capability... transform all of the
86 // add instruction uses into getelementptr's.
87 while (!CI.use_empty()) {
88 BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
89 assert(I->getOpcode() == Instruction::Add && I->getNumOperands() == 2 &&
90 "Use is not a valid add instruction!");
92 // Get the value added to the cast result pointer...
93 Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
95 Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
96 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
98 if (GEP->getType() == I->getType()) {
99 // Replace the old add instruction with the shiny new GEP inst
100 ReplaceInstWithInst(I, GEP);
102 // If the type produced by the gep instruction differs from the original
103 // add instruction type, insert a cast now.
106 // Insert the GEP instruction before the old add instruction...
107 I->getParent()->getInstList().insert(I, GEP);
109 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
110 GEP = new CastInst(GEP, I->getType());
112 // Replace the old add instruction with the shiny new GEP inst
113 ReplaceInstWithInst(I, GEP);
116 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
121 // Peephole optimize the following instructions:
122 // %t1 = cast ulong <const int> to {<...>} *
123 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
126 // %t1 = cast {<...>}* %SP to int*
127 // %t5 = cast ulong <const int> to int*
128 // %t2 = add int* %t1, %t5 ;; int is same size as field
130 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
131 // %t2 = cast <eltype> * %t3 to {<...>}*
133 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
134 Value *AddOp1, CastInst *AddOp2) {
135 const CompositeType *CompTy;
136 Value *OffsetVal = AddOp2->getOperand(0);
137 Value *SrcPtr; // Of type pointer to struct...
139 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
140 SrcPtr = AddOp1; // Handle the first case...
141 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
142 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
143 CompTy = getPointedToComposite(SrcPtr->getType());
146 // Only proceed if we have detected all of our conditions successfully...
147 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isIntegral())
150 std::vector<Value*> Indices;
151 if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
152 return false; // Not convertable... perhaps next time
154 if (getPointedToComposite(AddOp1->getType())) { // case 1
155 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
157 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
160 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
162 BI = ++BB->getInstList().insert(BI, GEP);
164 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
165 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
166 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
170 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
173 if (CastInst *CI = dyn_cast<CastInst>(I)) {
174 Value *Src = CI->getOperand(0);
175 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
176 const Type *DestTy = CI->getType();
178 // Peephole optimize the following instruction:
179 // %V2 = cast <ty> %V to <ty>
183 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
184 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
185 CI->replaceAllUsesWith(Src);
186 if (!Src->hasName() && CI->hasName()) {
187 std::string Name = CI->getName();
189 Src->setName(Name, BB->getParent()->getSymbolTable());
192 // DCE the instruction now, to avoid having the iterative version of DCE
193 // have to worry about it.
195 BI = BB->getInstList().erase(BI);
201 // Check to see if it's a cast of an instruction that does not depend on the
202 // specific type of the operands to do it's job.
203 if (!isReinterpretingCast(CI)) {
204 ValueTypeCache ConvertedTypes;
206 // Check to see if we can convert the source of the cast to match the
207 // destination type of the cast...
209 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
210 if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
211 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
213 DEBUG(cerr << "\nCONVERTING SRC EXPR TYPE:\n");
214 ValueMapCache ValueMap;
215 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
216 if (Constant *CPV = dyn_cast<Constant>(E))
217 CI->replaceAllUsesWith(CPV);
219 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
220 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
221 DEBUG(cerr << "DONE CONVERTING SRC EXPR TYPE: \n" << BB->getParent());
226 // Check to see if we can convert the users of the cast value to match the
227 // source type of the cast...
229 ConvertedTypes.clear();
230 if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
231 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
233 DEBUG(cerr << "\nCONVERTING EXPR TYPE:\n");
234 ValueMapCache ValueMap;
235 ConvertValueToNewType(CI, Src, ValueMap); // This will delete CI!
237 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
238 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
239 DEBUG(cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
245 // Otherwise find out it this cast is a cast to a pointer type, which is
246 // then added to some other pointer, then loaded or stored through. If
247 // so, convert the add into a getelementptr instruction...
249 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
250 if (HandleCastToPointer(BI, DestPTy)) {
251 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
257 // Check to see if we are casting from a structure pointer to a pointer to
258 // the first element of the structure... to avoid munching other peepholes,
259 // we only let this happen if there are no add uses of the cast.
261 // Peephole optimize the following instructions:
262 // %t1 = cast {<...>} * %StructPtr to <ty> *
264 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
265 // %t1 = cast <eltype> * %t1 to <ty> *
267 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
268 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
270 // Loop over uses of the cast, checking for add instructions. If an add
271 // exists, this is probably a part of a more complex GEP, so we don't
272 // want to mess around with the cast.
274 bool HasAddUse = false;
275 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
277 if (isa<Instruction>(*I) &&
278 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
279 HasAddUse = true; break;
282 // If it doesn't have an add use, check to see if the dest type is
283 // losslessly convertable to one of the types in the start of the struct
287 const Type *DestPointedTy = DestPTy->getElementType();
289 const CompositeType *CurCTy = CTy;
290 const Type *ElTy = 0;
292 // Build the index vector, full of all zeros
293 std::vector<Value*> Indices;
294 Indices.push_back(ConstantUInt::get(Type::UIntTy, 0));
295 while (CurCTy && !isa<PointerType>(CurCTy)) {
296 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
297 // Check for a zero element struct type... if we have one, bail.
298 if (CurSTy->getElementTypes().size() == 0) break;
300 // Grab the first element of the struct type, which must lie at
301 // offset zero in the struct.
303 ElTy = CurSTy->getElementTypes()[0];
305 ElTy = cast<ArrayType>(CurCTy)->getElementType();
308 // Insert a zero to index through this type...
309 Indices.push_back(ConstantUInt::get(CurCTy->getIndexType(), 0));
311 // Did we find what we're looking for?
312 if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
314 // Nope, go a level deeper.
316 CurCTy = dyn_cast<CompositeType>(ElTy);
320 // Did we find what we were looking for? If so, do the transformation
322 PRINT_PEEPHOLE1("cast-for-first:in", CI);
324 // Insert the new T cast instruction... stealing old T's name
325 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
328 BI = ++BB->getInstList().insert(BI, GEP);
330 // Make the old cast instruction reference the new GEP instead of
331 // the old src value.
333 CI->setOperand(0, GEP);
335 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
342 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
343 Value *Val = SI->getOperand(0);
344 Value *Pointer = SI->getPointerOperand();
346 // Peephole optimize the following instructions:
347 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
348 // store <T2> %V, <T2>* %t
351 // %t = cast <T2> %V to <T1>
352 // store <T1> %t2, <T1>* %P
354 // Note: This is not taken care of by expr conversion because there might
355 // not be a cast available for the store to convert the incoming value of.
356 // This code is basically here to make sure that pointers don't have casts
359 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
360 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
361 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
362 // convertable types?
363 if (Val->getType()->isLosslesslyConvertableTo(CSPT->getElementType()) &&
364 !SI->hasIndices()) { // No subscripts yet!
365 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
367 // Insert the new T cast instruction... stealing old T's name
368 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
371 BI = ++BB->getInstList().insert(BI, NCI);
373 // Replace the old store with a new one!
374 ReplaceInstWithInst(BB->getInstList(), BI,
375 SI = new StoreInst(NCI, CastSrc));
376 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
377 ++NumLoadStorePeepholes;
381 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
382 Value *Pointer = LI->getOperand(0);
383 const Type *PtrElType =
384 cast<PointerType>(Pointer->getType())->getElementType();
386 // Peephole optimize the following instructions:
387 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertable to T2
388 // %t = load <T2>* %P
391 // %t = load <T1>* %P
392 // %Val = cast <T1> to <T2>
394 // Note: This is not taken care of by expr conversion because there might
395 // not be a cast available for the store to convert the incoming value of.
396 // This code is basically here to make sure that pointers don't have casts
399 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
400 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
401 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
402 // convertable types?
403 if (PtrElType->isLosslesslyConvertableTo(CSPT->getElementType()) &&
404 !LI->hasIndices()) { // No subscripts yet!
405 PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
407 // Create the new load instruction... loading the pre-casted value
408 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName());
410 // Insert the new T cast instruction... stealing old T's name
411 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
412 BI = ++BB->getInstList().insert(BI, NewLI);
414 // Replace the old store with a new one!
415 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
416 PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
417 ++NumLoadStorePeepholes;
421 } else if (I->getOpcode() == Instruction::Add &&
422 isa<CastInst>(I->getOperand(1))) {
424 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
425 cast<CastInst>(I->getOperand(1)))) {
437 static bool DoRaisePass(Function &F) {
438 bool Changed = false;
439 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
440 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
441 DEBUG(cerr << "Processing: " << *BI);
442 if (dceInstruction(BI) || doConstantPropogation(BI)) {
445 DEBUG(cerr << "***\t\t^^-- DeadCode Elinated!\n");
446 } else if (PeepholeOptimize(BB, BI)) {
457 // RaisePointerReferences::doit - Raise a function representation to a higher
460 static bool doRPR(Function &F) {
461 DEBUG(cerr << "\n\n\nStarting to work on Function '" << F.getName() << "'\n");
463 // Insert casts for all incoming pointer pointer values that are treated as
466 bool Changed = false, LocalChange;
469 DEBUG(cerr << "Looping: \n" << F);
471 // Iterate over the function, refining it, until it converges on a stable
474 while (DoRaisePass(F)) LocalChange = true;
475 Changed |= LocalChange;
477 } while (LocalChange);
483 struct RaisePointerReferences : public FunctionPass {
484 const char *getPassName() const { return "Raise Pointer References"; }
486 virtual bool runOnFunction(Function &F) { return doRPR(F); }
488 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
494 Pass *createRaisePointerReferencesPass() {
495 return new RaisePointerReferences();