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 NumVarargCallChanges("raise", "Number of vararg call peepholes");
52 #define PRINT_PEEPHOLE(ID, NUM, I) \
53 DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
55 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
56 #define PRINT_PEEPHOLE2(ID, I1, I2) \
57 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
58 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
59 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
60 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
61 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
62 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
63 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
66 // isReinterpretingCast - Return true if the cast instruction specified will
67 // cause the operand to be "reinterpreted". A value is reinterpreted if the
68 // cast instruction would cause the underlying bits to change.
70 static inline bool isReinterpretingCast(const CastInst *CI) {
71 return!CI->getOperand(0)->getType()->isLosslesslyConvertableTo(CI->getType());
75 // Peephole optimize the following instructions:
76 // %t1 = cast ? to x *
77 // %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
79 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
80 // %t2 = cast <eltype> * %t3 to {<...>}*
82 static bool HandleCastToPointer(BasicBlock::iterator BI,
83 const PointerType *DestPTy) {
84 CastInst &CI = cast<CastInst>(*BI);
85 if (CI.use_empty()) return false;
87 // Scan all of the uses, looking for any uses that are not add
88 // instructions. If we have non-adds, do not make this transformation.
90 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
92 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
93 if (BO->getOpcode() != Instruction::Add ||
94 // Avoid add sbyte* %X, %X cases...
95 BO->getOperand(0) == BO->getOperand(1))
102 std::vector<Value*> Indices;
103 Value *Src = CI.getOperand(0);
104 const Type *Result = ConvertableToGEP(DestPTy, Src, Indices, &BI);
105 if (Result == 0) return false; // Not convertable...
107 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
109 // If we have a getelementptr capability... transform all of the
110 // add instruction uses into getelementptr's.
111 while (!CI.use_empty()) {
112 BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
113 assert(I->getOpcode() == Instruction::Add && I->getNumOperands() == 2 &&
114 "Use is not a valid add instruction!");
116 // Get the value added to the cast result pointer...
117 Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
119 Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
120 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
122 if (GEP->getType() == I->getType()) {
123 // Replace the old add instruction with the shiny new GEP inst
124 ReplaceInstWithInst(I, GEP);
126 // If the type produced by the gep instruction differs from the original
127 // add instruction type, insert a cast now.
130 // Insert the GEP instruction before the old add instruction...
131 I->getParent()->getInstList().insert(I, GEP);
133 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
134 GEP = new CastInst(GEP, I->getType());
136 // Replace the old add instruction with the shiny new GEP inst
137 ReplaceInstWithInst(I, GEP);
140 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
145 // Peephole optimize the following instructions:
146 // %t1 = cast ulong <const int> to {<...>} *
147 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
150 // %t1 = cast {<...>}* %SP to int*
151 // %t5 = cast ulong <const int> to int*
152 // %t2 = add int* %t1, %t5 ;; int is same size as field
154 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
155 // %t2 = cast <eltype> * %t3 to {<...>}*
157 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
158 Value *AddOp1, CastInst *AddOp2) {
159 const CompositeType *CompTy;
160 Value *OffsetVal = AddOp2->getOperand(0);
161 Value *SrcPtr = 0; // Of type pointer to struct...
163 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
164 SrcPtr = AddOp1; // Handle the first case...
165 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
166 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
167 CompTy = getPointedToComposite(SrcPtr->getType());
170 // Only proceed if we have detected all of our conditions successfully...
171 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isInteger())
174 std::vector<Value*> Indices;
175 if (!ConvertableToGEP(SrcPtr->getType(), OffsetVal, Indices, &BI))
176 return false; // Not convertable... perhaps next time
178 if (getPointedToComposite(AddOp1->getType())) { // case 1
179 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
181 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
184 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
185 AddOp2->getName(), BI);
187 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
188 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
189 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
193 static bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
196 if (CastInst *CI = dyn_cast<CastInst>(I)) {
197 Value *Src = CI->getOperand(0);
198 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
199 const Type *DestTy = CI->getType();
201 // Peephole optimize the following instruction:
202 // %V2 = cast <ty> %V to <ty>
206 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
207 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
208 CI->replaceAllUsesWith(Src);
209 if (!Src->hasName() && CI->hasName()) {
210 std::string Name = CI->getName();
212 Src->setName(Name, &BB->getParent()->getSymbolTable());
215 // DCE the instruction now, to avoid having the iterative version of DCE
216 // have to worry about it.
218 BI = BB->getInstList().erase(BI);
224 // Check to see if it's a cast of an instruction that does not depend on the
225 // specific type of the operands to do it's job.
226 if (!isReinterpretingCast(CI)) {
227 ValueTypeCache ConvertedTypes;
229 // Check to see if we can convert the source of the cast to match the
230 // destination type of the cast...
232 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
233 if (ExpressionConvertableToType(Src, DestTy, ConvertedTypes)) {
234 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
236 DEBUG(cerr << "\nCONVERTING SRC EXPR TYPE:\n");
237 { // ValueMap must be destroyed before function verified!
238 ValueMapCache ValueMap;
239 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap);
241 if (Constant *CPV = dyn_cast<Constant>(E))
242 CI->replaceAllUsesWith(CPV);
244 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
245 DEBUG(cerr << "DONE CONVERTING SRC EXPR TYPE: \n" << BB->getParent());
248 DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
249 "Function broken!"));
250 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
255 // Check to see if we can convert the users of the cast value to match the
256 // source type of the cast...
258 ConvertedTypes.clear();
259 // Make sure the source doesn't change type
260 ConvertedTypes[Src] = Src->getType();
261 if (ValueConvertableToType(CI, Src->getType(), ConvertedTypes)) {
262 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
264 DEBUG(cerr << "\nCONVERTING EXPR TYPE:\n");
265 { // ValueMap must be destroyed before function verified!
266 ValueMapCache ValueMap;
267 ConvertValueToNewType(CI, Src, ValueMap); // This will delete CI!
270 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
271 DEBUG(cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
273 DEBUG(assert(verifyFunction(*BB->getParent()) == false &&
274 "Function broken!"));
275 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
281 // Otherwise find out it this cast is a cast to a pointer type, which is
282 // then added to some other pointer, then loaded or stored through. If
283 // so, convert the add into a getelementptr instruction...
285 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
286 if (HandleCastToPointer(BI, DestPTy)) {
287 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
293 // Check to see if we are casting from a structure pointer to a pointer to
294 // the first element of the structure... to avoid munching other peepholes,
295 // we only let this happen if there are no add uses of the cast.
297 // Peephole optimize the following instructions:
298 // %t1 = cast {<...>} * %StructPtr to <ty> *
300 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
301 // %t1 = cast <eltype> * %t1 to <ty> *
303 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
304 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
306 // Loop over uses of the cast, checking for add instructions. If an add
307 // exists, this is probably a part of a more complex GEP, so we don't
308 // want to mess around with the cast.
310 bool HasAddUse = false;
311 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
313 if (isa<Instruction>(*I) &&
314 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
315 HasAddUse = true; break;
318 // If it doesn't have an add use, check to see if the dest type is
319 // losslessly convertable to one of the types in the start of the struct
323 const Type *DestPointedTy = DestPTy->getElementType();
325 const CompositeType *CurCTy = CTy;
326 const Type *ElTy = 0;
328 // Build the index vector, full of all zeros
329 std::vector<Value*> Indices;
330 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
331 while (CurCTy && !isa<PointerType>(CurCTy)) {
332 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
333 // Check for a zero element struct type... if we have one, bail.
334 if (CurSTy->getElementTypes().size() == 0) break;
336 // Grab the first element of the struct type, which must lie at
337 // offset zero in the struct.
339 ElTy = CurSTy->getElementTypes()[0];
341 ElTy = cast<ArrayType>(CurCTy)->getElementType();
344 // Insert a zero to index through this type...
345 Indices.push_back(Constant::getNullValue(CurCTy->getIndexType()));
347 // Did we find what we're looking for?
348 if (ElTy->isLosslesslyConvertableTo(DestPointedTy)) break;
350 // Nope, go a level deeper.
352 CurCTy = dyn_cast<CompositeType>(ElTy);
356 // Did we find what we were looking for? If so, do the transformation
358 PRINT_PEEPHOLE1("cast-for-first:in", CI);
360 std::string Name = CI->getName(); CI->setName("");
362 // Insert the new T cast instruction... stealing old T's name
363 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
366 // Make the old cast instruction reference the new GEP instead of
367 // the old src value.
369 CI->setOperand(0, GEP);
371 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
378 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
379 Value *Val = SI->getOperand(0);
380 Value *Pointer = SI->getPointerOperand();
382 // Peephole optimize the following instructions:
383 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertable to T2
384 // store <T2> %V, <T2>* %t
387 // %t = cast <T2> %V to <T1>
388 // store <T1> %t2, <T1>* %P
390 // Note: This is not taken care of by expr conversion because there might
391 // not be a cast available for the store to convert the incoming value of.
392 // This code is basically here to make sure that pointers don't have casts
395 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
396 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
397 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
398 // convertable types?
399 if (Val->getType()->isLosslesslyConvertableTo(CSPT->getElementType())) {
400 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
402 // Insert the new T cast instruction... stealing old T's name
403 std::string Name(CI->getName()); CI->setName("");
404 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
407 // Replace the old store with a new one!
408 ReplaceInstWithInst(BB->getInstList(), BI,
409 SI = new StoreInst(NCI, CastSrc));
410 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
411 ++NumLoadStorePeepholes;
415 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
416 Value *Pointer = LI->getOperand(0);
417 const Type *PtrElType =
418 cast<PointerType>(Pointer->getType())->getElementType();
420 // Peephole optimize the following instructions:
421 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertable to T2
422 // %t = load <T2>* %P
425 // %t = load <T1>* %P
426 // %Val = cast <T1> to <T2>
428 // Note: This is not taken care of by expr conversion because there might
429 // not be a cast available for the store to convert the incoming value of.
430 // This code is basically here to make sure that pointers don't have casts
433 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
434 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
435 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
436 // convertable types?
437 if (PtrElType->isLosslesslyConvertableTo(CSPT->getElementType())) {
438 PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
440 // Create the new load instruction... loading the pre-casted value
441 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
443 // Insert the new T cast instruction... stealing old T's name
444 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
446 // Replace the old store with a new one!
447 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
448 PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
449 ++NumLoadStorePeepholes;
453 } else if (I->getOpcode() == Instruction::Add &&
454 isa<CastInst>(I->getOperand(1))) {
456 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
457 cast<CastInst>(I->getOperand(1)))) {
461 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
462 // If we have a call with all varargs arguments, convert the call to use the
463 // actual argument types present...
465 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
466 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
468 // Is the call to a vararg variable with no real parameters?
469 if (FTy->isVarArg() && FTy->getNumParams() == 0) {
470 // If so, insert a new cast instruction, casting it to a function type
471 // that matches the current arguments...
473 std::vector<const Type *> Params; // Parameter types...
474 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
475 Params.push_back(CI->getOperand(i)->getType());
477 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
479 PointerType *NewPFunTy = PointerType::get(NewFT);
481 // Create a new cast, inserting it right before the function call...
482 CastInst *NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
483 CI->getCalledValue()->getName(), CI);
485 // Create a new call instruction...
486 CallInst *NewCall = new CallInst(NewCast,
487 std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
489 ReplaceInstWithInst(CI, NewCall);
491 ++NumVarargCallChanges;
503 static bool DoRaisePass(Function &F) {
504 bool Changed = false;
505 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
506 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
507 DEBUG(cerr << "Processing: " << *BI);
508 if (dceInstruction(BI) || doConstantPropogation(BI)) {
511 DEBUG(cerr << "***\t\t^^-- Dead code eliminated!\n");
512 } else if (PeepholeOptimize(BB, BI)) {
523 // RaisePointerReferences::doit - Raise a function representation to a higher
526 static bool doRPR(Function &F) {
527 DEBUG(cerr << "\n\n\nStarting to work on Function '" << F.getName() << "'\n");
529 // Insert casts for all incoming pointer pointer values that are treated as
532 bool Changed = false, LocalChange;
535 // If the StartInst option was specified, then Peephole optimize that
536 // instruction first if it occurs in this function.
538 if (!StartInst.empty()) {
539 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
540 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
541 if (BI->getName() == StartInst) {
542 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
543 DebugFlag = true; // Turn on DEBUG's
544 Changed |= PeepholeOptimize(BB, BI);
545 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
550 DEBUG(cerr << "Looping: \n" << F);
552 // Iterate over the function, refining it, until it converges on a stable
555 while (DoRaisePass(F)) LocalChange = true;
556 Changed |= LocalChange;
558 } while (LocalChange);
564 struct RaisePointerReferences : public FunctionPass {
566 // FIXME: constructor should save and use target data here!!
567 RaisePointerReferences(const TargetData &TD) {}
569 virtual bool runOnFunction(Function &F) { return doRPR(F); }
571 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
572 AU.setPreservesCFG();
577 Pass *createRaisePointerReferencesPass(const TargetData &TD) {
578 return new RaisePointerReferences(TD);
581 static RegisterOpt<RaisePointerReferences>
582 X("raise", "Raise Pointer References", createRaisePointerReferencesPass);