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/RaisePointerReferences.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/Analysis/Verifier.h"
18 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
19 #include "Support/STLExtras.h"
20 #include "Support/Statistic.h"
21 #include "Support/CommandLine.h"
25 // StartInst - This enables the -raise-start-inst=foo option to cause the level
26 // raising pass to start at instruction "foo", which is immensely useful for
29 static cl::opt<std::string>
30 StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
31 cl::desc("Start raise pass at the instruction with the specified name"));
34 NumLoadStorePeepholes("raise", "Number of load/store peepholes");
37 NumGEPInstFormed("raise", "Number of other getelementptr's formed");
40 NumExprTreesConv("raise", "Number of expression trees converted");
43 NumCastOfCast("raise", "Number of cast-of-self removed");
46 NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
49 #define PRINT_PEEPHOLE(ID, NUM, I) \
50 DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
52 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
53 #define PRINT_PEEPHOLE2(ID, I1, I2) \
54 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
55 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
56 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
57 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
58 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
59 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
60 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
63 // isReinterpretingCast - Return true if the cast instruction specified will
64 // cause the operand to be "reinterpreted". A value is reinterpreted if the
65 // cast instruction would cause the underlying bits to change.
67 static inline bool isReinterpretingCast(const CastInst *CI) {
68 return!CI->getOperand(0)->getType()->isLosslesslyConvertableTo(CI->getType());
72 // Peephole optimize the following instructions:
73 // %t1 = cast ? to x *
74 // %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
76 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
77 // %t2 = cast <eltype> * %t3 to {<...>}*
79 static bool HandleCastToPointer(BasicBlock::iterator BI,
80 const PointerType *DestPTy) {
81 CastInst &CI = cast<CastInst>(*BI);
82 if (CI.use_empty()) return false;
84 // Scan all of the uses, looking for any uses that are not add
85 // instructions. If we have non-adds, do not make this transformation.
87 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
89 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
90 if (BO->getOpcode() != Instruction::Add ||
91 // Avoid add sbyte* %X, %X cases...
92 BO->getOperand(0) == BO->getOperand(1))
99 std::vector<Value*> Indices;
100 Value *Src = CI.getOperand(0);
101 const Type *Result = ConvertableToGEP(DestPTy, Src, Indices, &BI);
102 if (Result == 0) return false; // Not convertable...
104 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
106 // If we have a getelementptr capability... transform all of the
107 // add instruction uses into getelementptr's.
108 while (!CI.use_empty()) {
109 BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
110 assert(I->getOpcode() == Instruction::Add && I->getNumOperands() == 2 &&
111 "Use is not a valid add instruction!");
113 // Get the value added to the cast result pointer...
114 Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
116 Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
117 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
119 if (GEP->getType() == I->getType()) {
120 // Replace the old add instruction with the shiny new GEP inst
121 ReplaceInstWithInst(I, GEP);
123 // If the type produced by the gep instruction differs from the original
124 // add instruction type, insert a cast now.
127 // Insert the GEP instruction before the old add instruction...
128 I->getParent()->getInstList().insert(I, GEP);
130 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
131 GEP = new CastInst(GEP, I->getType());
133 // Replace the old add instruction with the shiny new GEP inst
134 ReplaceInstWithInst(I, GEP);
137 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
142 // Peephole optimize the following instructions:
143 // %t1 = cast ulong <const int> to {<...>} *
144 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
147 // %t1 = cast {<...>}* %SP to int*
148 // %t5 = cast ulong <const int> to int*
149 // %t2 = add int* %t1, %t5 ;; int is same size as field
151 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
152 // %t2 = cast <eltype> * %t3 to {<...>}*
154 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
155 Value *AddOp1, CastInst *AddOp2) {
156 const CompositeType *CompTy;
157 Value *OffsetVal = AddOp2->getOperand(0);
158 Value *SrcPtr; // Of type pointer to struct...
160 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
161 SrcPtr = AddOp1; // Handle the first case...
162 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
163 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
164 CompTy = getPointedToComposite(SrcPtr->getType());
167 // Only proceed if we have detected all of our conditions successfully...
168 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isInteger())
171 std::vector<Value*> Indices;
172 if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
173 return false; // Not convertable... perhaps next time
175 if (getPointedToComposite(AddOp1->getType())) { // case 1
176 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
178 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
181 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
182 AddOp2->getName(), BI);
184 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
185 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
186 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
190 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
193 if (CastInst *CI = dyn_cast<CastInst>(I)) {
194 Value *Src = CI->getOperand(0);
195 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
196 const Type *DestTy = CI->getType();
198 // Peephole optimize the following instruction:
199 // %V2 = cast <ty> %V to <ty>
203 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
204 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
205 CI->replaceAllUsesWith(Src);
206 if (!Src->hasName() && CI->hasName()) {
207 std::string Name = CI->getName();
209 Src->setName(Name, BB->getParent()->getSymbolTable());
212 // DCE the instruction now, to avoid having the iterative version of DCE
213 // have to worry about it.
215 BI = BB->getInstList().erase(BI);
221 // Check to see if it's a cast of an instruction that does not depend on the
222 // specific type of the operands to do it's job.
223 if (!isReinterpretingCast(CI)) {
224 ValueTypeCache ConvertedTypes;
226 // Check to see if we can convert the source of the cast to match the
227 // destination type of the cast...
229 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
230 if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
231 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
233 DEBUG(cerr << "\nCONVERTING SRC EXPR TYPE:\n");
234 { // ValueMap must be destroyed before function verified!
235 ValueMapCache ValueMap;
236 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
238 if (Constant *CPV = dyn_cast<Constant>(E))
239 CI->replaceAllUsesWith(CPV);
241 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
242 DEBUG(cerr << "DONE CONVERTING SRC EXPR TYPE: \n" << BB->getParent());
245 DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
246 "Function broken!"));
247 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
252 // Check to see if we can convert the users of the cast value to match the
253 // source type of the cast...
255 ConvertedTypes.clear();
256 ConvertedTypes[Src] = Src->getType(); // Make sure the source doesn't change type
257 if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
258 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
260 DEBUG(cerr << "\nCONVERTING EXPR TYPE:\n");
261 { // ValueMap must be destroyed before function verified!
262 ValueMapCache ValueMap;
263 ConvertValueToNewType(CI, Src, ValueMap); // This will delete CI!
266 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
267 DEBUG(cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
269 DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
270 "Function broken!"));
271 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
277 // Otherwise find out it this cast is a cast to a pointer type, which is
278 // then added to some other pointer, then loaded or stored through. If
279 // so, convert the add into a getelementptr instruction...
281 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
282 if (HandleCastToPointer(BI, DestPTy)) {
283 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
289 // Check to see if we are casting from a structure pointer to a pointer to
290 // the first element of the structure... to avoid munching other peepholes,
291 // we only let this happen if there are no add uses of the cast.
293 // Peephole optimize the following instructions:
294 // %t1 = cast {<...>} * %StructPtr to <ty> *
296 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
297 // %t1 = cast <eltype> * %t1 to <ty> *
299 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
300 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
302 // Loop over uses of the cast, checking for add instructions. If an add
303 // exists, this is probably a part of a more complex GEP, so we don't
304 // want to mess around with the cast.
306 bool HasAddUse = false;
307 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
309 if (isa<Instruction>(*I) &&
310 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
311 HasAddUse = true; break;
314 // If it doesn't have an add use, check to see if the dest type is
315 // losslessly convertable to one of the types in the start of the struct
319 const Type *DestPointedTy = DestPTy->getElementType();
321 const CompositeType *CurCTy = CTy;
322 const Type *ElTy = 0;
324 // Build the index vector, full of all zeros
325 std::vector<Value*> Indices;
326 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
327 while (CurCTy && !isa<PointerType>(CurCTy)) {
328 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
329 // Check for a zero element struct type... if we have one, bail.
330 if (CurSTy->getElementTypes().size() == 0) break;
332 // Grab the first element of the struct type, which must lie at
333 // offset zero in the struct.
335 ElTy = CurSTy->getElementTypes()[0];
337 ElTy = cast<ArrayType>(CurCTy)->getElementType();
340 // Insert a zero to index through this type...
341 Indices.push_back(Constant::getNullValue(CurCTy->getIndexType()));
343 // Did we find what we're looking for?
344 if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
346 // Nope, go a level deeper.
348 CurCTy = dyn_cast<CompositeType>(ElTy);
352 // Did we find what we were looking for? If so, do the transformation
354 PRINT_PEEPHOLE1("cast-for-first:in", CI);
356 std::string Name = CI->getName(); CI->setName("");
358 // Insert the new T cast instruction... stealing old T's name
359 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
362 // Make the old cast instruction reference the new GEP instead of
363 // the old src value.
365 CI->setOperand(0, GEP);
367 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
374 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
375 Value *Val = SI->getOperand(0);
376 Value *Pointer = SI->getPointerOperand();
378 // Peephole optimize the following instructions:
379 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
380 // store <T2> %V, <T2>* %t
383 // %t = cast <T2> %V to <T1>
384 // store <T1> %t2, <T1>* %P
386 // Note: This is not taken care of by expr conversion because there might
387 // not be a cast available for the store to convert the incoming value of.
388 // This code is basically here to make sure that pointers don't have casts
391 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
392 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
393 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
394 // convertable types?
395 if (Val->getType()->isLosslesslyConvertableTo(CSPT->getElementType())) {
396 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
398 // Insert the new T cast instruction... stealing old T's name
399 std::string Name(CI->getName()); CI->setName("");
400 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
403 // Replace the old store with a new one!
404 ReplaceInstWithInst(BB->getInstList(), BI,
405 SI = new StoreInst(NCI, CastSrc));
406 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
407 ++NumLoadStorePeepholes;
411 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
412 Value *Pointer = LI->getOperand(0);
413 const Type *PtrElType =
414 cast<PointerType>(Pointer->getType())->getElementType();
416 // Peephole optimize the following instructions:
417 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertable to T2
418 // %t = load <T2>* %P
421 // %t = load <T1>* %P
422 // %Val = cast <T1> to <T2>
424 // Note: This is not taken care of by expr conversion because there might
425 // not be a cast available for the store to convert the incoming value of.
426 // This code is basically here to make sure that pointers don't have casts
429 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
430 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
431 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
432 // convertable types?
433 if (PtrElType->isLosslesslyConvertableTo(CSPT->getElementType())) {
434 PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
436 // Create the new load instruction... loading the pre-casted value
437 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
439 // Insert the new T cast instruction... stealing old T's name
440 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
442 // Replace the old store with a new one!
443 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
444 PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
445 ++NumLoadStorePeepholes;
449 } else if (I->getOpcode() == Instruction::Add &&
450 isa<CastInst>(I->getOperand(1))) {
452 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
453 cast<CastInst>(I->getOperand(1)))) {
465 static bool DoRaisePass(Function &F) {
466 bool Changed = false;
467 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
468 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
469 DEBUG(cerr << "Processing: " << *BI);
470 if (dceInstruction(BI) || doConstantPropogation(BI)) {
473 DEBUG(cerr << "***\t\t^^-- Dead code eliminated!\n");
474 } else if (PeepholeOptimize(BB, BI)) {
485 // RaisePointerReferences::doit - Raise a function representation to a higher
488 static bool doRPR(Function &F) {
489 DEBUG(cerr << "\n\n\nStarting to work on Function '" << F.getName() << "'\n");
491 // Insert casts for all incoming pointer pointer values that are treated as
494 bool Changed = false, LocalChange;
497 // If the StartInst option was specified, then Peephole optimize that
498 // instruction first if it occurs in this function.
500 if (!StartInst.empty()) {
501 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
502 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
503 if (BI->getName() == StartInst) {
504 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
505 DebugFlag = true; // Turn on DEBUG's
506 Changed |= PeepholeOptimize(BB, BI);
507 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
512 DEBUG(cerr << "Looping: \n" << F);
514 // Iterate over the function, refining it, until it converges on a stable
517 while (DoRaisePass(F)) LocalChange = true;
518 Changed |= LocalChange;
520 } while (LocalChange);
526 struct RaisePointerReferences : public FunctionPass {
528 // FIXME: constructor should save and use target data here!!
529 RaisePointerReferences(const TargetData &TD) {}
531 virtual bool runOnFunction(Function &F) { return doRPR(F); }
533 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
539 Pass *createRaisePointerReferencesPass(const TargetData &TD) {
540 return new RaisePointerReferences(TD);
543 static RegisterOpt<RaisePointerReferences>
544 X("raise", "Raise Pointer References", createRaisePointerReferencesPass);