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/iOther.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
23 #include "Support/CommandLine.h"
24 #include "Support/Debug.h"
25 #include "Support/Statistic.h"
26 #include "Support/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 Pass *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());
101 // Peephole optimize the following instructions:
102 // %t1 = cast ? to x *
103 // %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
105 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
106 // %t2 = cast <eltype> * %t3 to {<...>}*
108 static bool HandleCastToPointer(BasicBlock::iterator BI,
109 const PointerType *DestPTy,
110 const TargetData &TD) {
111 CastInst &CI = cast<CastInst>(*BI);
112 if (CI.use_empty()) return false;
114 // Scan all of the uses, looking for any uses that are not add or sub
115 // instructions. If we have non-adds, do not make this transformation.
117 bool HasSubUse = false; // Keep track of any subtracts...
118 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
120 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
121 if ((BO->getOpcode() != Instruction::Add &&
122 BO->getOpcode() != Instruction::Sub) ||
123 // Avoid add sbyte* %X, %X cases...
124 BO->getOperand(0) == BO->getOperand(1))
127 HasSubUse |= BO->getOpcode() == Instruction::Sub;
132 std::vector<Value*> Indices;
133 Value *Src = CI.getOperand(0);
134 const Type *Result = ConvertibleToGEP(DestPTy, Src, Indices, TD, &BI);
135 if (Result == 0) return false; // Not convertible...
137 // Cannot handle subtracts if there is more than one index required...
138 if (HasSubUse && Indices.size() != 1) return false;
140 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
142 // If we have a getelementptr capability... transform all of the
143 // add instruction uses into getelementptr's.
144 while (!CI.use_empty()) {
145 BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
146 assert((I->getOpcode() == Instruction::Add ||
147 I->getOpcode() == Instruction::Sub) &&
148 "Use is not a valid add instruction!");
150 // Get the value added to the cast result pointer...
151 Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
153 Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
154 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
156 // If the instruction is actually a subtract, we are guaranteed to only have
157 // one index (from code above), so we just need to negate the pointer index
159 if (I->getOpcode() == Instruction::Sub) {
160 Instruction *Neg = BinaryOperator::createNeg(GEP->getOperand(1),
161 GEP->getOperand(1)->getName()+".neg", I);
162 GEP->setOperand(1, Neg);
165 if (GEP->getType() == I->getType()) {
166 // Replace the old add instruction with the shiny new GEP inst
167 ReplaceInstWithInst(I, GEP);
169 // If the type produced by the gep instruction differs from the original
170 // add instruction type, insert a cast now.
173 // Insert the GEP instruction before the old add instruction...
174 I->getParent()->getInstList().insert(I, GEP);
176 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
177 GEP = new CastInst(GEP, I->getType());
179 // Replace the old add instruction with the shiny new GEP inst
180 ReplaceInstWithInst(I, GEP);
183 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
188 // Peephole optimize the following instructions:
189 // %t1 = cast ulong <const int> to {<...>} *
190 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
193 // %t1 = cast {<...>}* %SP to int*
194 // %t5 = cast ulong <const int> to int*
195 // %t2 = add int* %t1, %t5 ;; int is same size as field
197 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
198 // %t2 = cast <eltype> * %t3 to {<...>}*
200 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
201 Value *AddOp1, CastInst *AddOp2,
202 const TargetData &TD) {
203 const CompositeType *CompTy;
204 Value *OffsetVal = AddOp2->getOperand(0);
205 Value *SrcPtr = 0; // Of type pointer to struct...
207 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
208 SrcPtr = AddOp1; // Handle the first case...
209 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
210 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
211 CompTy = getPointedToComposite(SrcPtr->getType());
214 // Only proceed if we have detected all of our conditions successfully...
215 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isInteger())
218 std::vector<Value*> Indices;
219 if (!ConvertibleToGEP(SrcPtr->getType(), OffsetVal, Indices, TD, &BI))
220 return false; // Not convertible... perhaps next time
222 if (getPointedToComposite(AddOp1->getType())) { // case 1
223 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
225 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
228 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
229 AddOp2->getName(), BI);
231 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
232 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
233 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
237 bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
239 const TargetData &TD = getAnalysis<TargetData>();
241 if (CastInst *CI = dyn_cast<CastInst>(I)) {
242 Value *Src = CI->getOperand(0);
243 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
244 const Type *DestTy = CI->getType();
246 // Peephole optimize the following instruction:
247 // %V2 = cast <ty> %V to <ty>
251 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
252 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
253 CI->replaceAllUsesWith(Src);
254 if (!Src->hasName() && CI->hasName()) {
255 std::string Name = CI->getName();
257 Src->setName(Name, &BB->getParent()->getSymbolTable());
260 // DCE the instruction now, to avoid having the iterative version of DCE
261 // have to worry about it.
263 BI = BB->getInstList().erase(BI);
269 // Check to see if it's a cast of an instruction that does not depend on the
270 // specific type of the operands to do it's job.
271 if (!isReinterpretingCast(CI)) {
272 ValueTypeCache ConvertedTypes;
274 // Check to see if we can convert the source of the cast to match the
275 // destination type of the cast...
277 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
278 if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
279 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
281 DEBUG(std::cerr << "\nCONVERTING SRC EXPR TYPE:\n");
282 { // ValueMap must be destroyed before function verified!
283 ValueMapCache ValueMap;
284 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
286 if (Constant *CPV = dyn_cast<Constant>(E))
287 CI->replaceAllUsesWith(CPV);
289 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
290 DEBUG(std::cerr << "DONE CONVERTING SRC EXPR TYPE: \n"
294 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
299 // Check to see if we can convert the users of the cast value to match the
300 // source type of the cast...
302 ConvertedTypes.clear();
303 // Make sure the source doesn't change type
304 ConvertedTypes[Src] = Src->getType();
305 if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
306 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
308 DEBUG(std::cerr << "\nCONVERTING EXPR TYPE:\n");
309 { // ValueMap must be destroyed before function verified!
310 ValueMapCache ValueMap;
311 ConvertValueToNewType(CI, Src, ValueMap, TD); // This will delete CI!
314 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
315 DEBUG(std::cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
317 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
323 // Otherwise find out it this cast is a cast to a pointer type, which is
324 // then added to some other pointer, then loaded or stored through. If
325 // so, convert the add into a getelementptr instruction...
327 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
328 if (HandleCastToPointer(BI, DestPTy, TD)) {
329 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
335 // Check to see if we are casting from a structure pointer to a pointer to
336 // the first element of the structure... to avoid munching other peepholes,
337 // we only let this happen if there are no add uses of the cast.
339 // Peephole optimize the following instructions:
340 // %t1 = cast {<...>} * %StructPtr to <ty> *
342 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
343 // %t1 = cast <eltype> * %t1 to <ty> *
345 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
346 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
348 // Loop over uses of the cast, checking for add instructions. If an add
349 // exists, this is probably a part of a more complex GEP, so we don't
350 // want to mess around with the cast.
352 bool HasAddUse = false;
353 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
355 if (isa<Instruction>(*I) &&
356 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
357 HasAddUse = true; break;
360 // If it doesn't have an add use, check to see if the dest type is
361 // losslessly convertible to one of the types in the start of the struct
365 const Type *DestPointedTy = DestPTy->getElementType();
367 const CompositeType *CurCTy = CTy;
368 const Type *ElTy = 0;
370 // Build the index vector, full of all zeros
371 std::vector<Value*> Indices;
373 Indices.push_back(ConstantSInt::get(Type::LongTy, 0)); // FIXME, PR82
374 while (CurCTy && !isa<PointerType>(CurCTy)) {
376 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
377 // Check for a zero element struct type... if we have one, bail.
378 if (CurSTy->getNumElements() == 0) break;
380 // Grab the first element of the struct type, which must lie at
381 // offset zero in the struct.
383 ElTy = CurSTy->getElementType(0);
384 IdxType = Type::UByteTy; // FIXME when PR82 is fixed.
386 ElTy = cast<ArrayType>(CurCTy)->getElementType();
387 IdxType = Type::LongTy; // FIXME when PR82 is fixed.
390 // Insert a zero to index through this type...
391 Indices.push_back(Constant::getNullValue(IdxType));
393 // Did we find what we're looking for?
394 if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
396 // Nope, go a level deeper.
398 CurCTy = dyn_cast<CompositeType>(ElTy);
402 // Did we find what we were looking for? If so, do the transformation
404 PRINT_PEEPHOLE1("cast-for-first:in", CI);
406 std::string Name = CI->getName(); CI->setName("");
408 // Insert the new T cast instruction... stealing old T's name
409 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
412 // Make the old cast instruction reference the new GEP instead of
413 // the old src value.
415 CI->setOperand(0, GEP);
417 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
424 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
425 Value *Val = SI->getOperand(0);
426 Value *Pointer = SI->getPointerOperand();
428 // Peephole optimize the following instructions:
429 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
430 // store <T2> %V, <T2>* %t
433 // %t = cast <T2> %V to <T1>
434 // store <T1> %t2, <T1>* %P
436 // Note: This is not taken care of by expr conversion because there might
437 // not be a cast available for the store to convert the incoming value of.
438 // This code is basically here to make sure that pointers don't have casts
441 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
442 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
443 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
444 // convertible types?
445 if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
446 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
448 // Insert the new T cast instruction... stealing old T's name
449 std::string Name(CI->getName()); CI->setName("");
450 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
453 // Replace the old store with a new one!
454 ReplaceInstWithInst(BB->getInstList(), BI,
455 SI = new StoreInst(NCI, CastSrc));
456 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
457 ++NumLoadStorePeepholes;
461 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
462 Value *Pointer = LI->getOperand(0);
463 const Type *PtrElType =
464 cast<PointerType>(Pointer->getType())->getElementType();
466 // Peephole optimize the following instructions:
467 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertible to T2
468 // %t = load <T2>* %P
471 // %t = load <T1>* %P
472 // %Val = cast <T1> to <T2>
474 // Note: This is not taken care of by expr conversion because there might
475 // not be a cast available for the store to convert the incoming value of.
476 // This code is basically here to make sure that pointers don't have casts
479 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
480 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
481 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
482 // convertible types?
483 if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
484 PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
486 // Create the new load instruction... loading the pre-casted value
487 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
489 // Insert the new T cast instruction... stealing old T's name
490 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
492 // Replace the old store with a new one!
493 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
494 PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
495 ++NumLoadStorePeepholes;
499 } else if (I->getOpcode() == Instruction::Add &&
500 isa<CastInst>(I->getOperand(1))) {
502 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
503 cast<CastInst>(I->getOperand(1)), TD)) {
507 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
508 // If we have a call with all varargs arguments, convert the call to use the
509 // actual argument types present...
511 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
512 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
514 // Is the call to a vararg variable with no real parameters?
515 if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
516 !CI->getCalledFunction()) {
517 // If so, insert a new cast instruction, casting it to a function type
518 // that matches the current arguments...
520 std::vector<const Type *> Params; // Parameter types...
521 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
522 Params.push_back(CI->getOperand(i)->getType());
524 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
526 PointerType *NewPFunTy = PointerType::get(NewFT);
528 // Create a new cast, inserting it right before the function call...
530 Constant *ConstantCallSrc = 0;
531 if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
532 ConstantCallSrc = CS;
533 else if (GlobalValue *GV = dyn_cast<GlobalValue>(CI->getCalledValue()))
534 ConstantCallSrc = ConstantPointerRef::get(GV);
537 NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
539 NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
540 CI->getCalledValue()->getName()+"_c",CI);
542 // Strip off unneeded CPR's.
543 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(NewCast))
544 NewCast = CPR->getValue();
546 // Create a new call instruction...
547 CallInst *NewCall = new CallInst(NewCast,
548 std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
550 ReplaceInstWithInst(CI, NewCall);
552 ++NumVarargCallChanges;
564 bool RPR::DoRaisePass(Function &F) {
565 bool Changed = false;
566 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
567 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
568 DEBUG(std::cerr << "Processing: " << *BI);
569 if (dceInstruction(BI) || doConstantPropagation(BI)) {
572 DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
573 } else if (PeepholeOptimize(BB, BI)) {
584 // runOnFunction - Raise a function representation to a higher level.
585 bool RPR::runOnFunction(Function &F) {
586 DEBUG(std::cerr << "\n\n\nStarting to work on Function '" << F.getName()
589 // Insert casts for all incoming pointer pointer values that are treated as
592 bool Changed = false, LocalChange;
594 // If the StartInst option was specified, then Peephole optimize that
595 // instruction first if it occurs in this function.
597 if (!StartInst.empty()) {
598 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
599 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
600 if (BI->getName() == StartInst) {
601 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
602 DebugFlag = true; // Turn on DEBUG's
603 Changed |= PeepholeOptimize(BB, BI);
604 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
609 DEBUG(std::cerr << "Looping: \n" << F);
611 // Iterate over the function, refining it, until it converges on a stable
614 while (DoRaisePass(F)) LocalChange = true;
615 Changed |= LocalChange;
617 } while (LocalChange);