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/ConstantHandling.h"
23 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
24 #include "Support/CommandLine.h"
25 #include "Support/Debug.h"
26 #include "Support/Statistic.h"
27 #include "Support/STLExtras.h"
31 // StartInst - This enables the -raise-start-inst=foo option to cause the level
32 // raising pass to start at instruction "foo", which is immensely useful for
35 static cl::opt<std::string>
36 StartInst("raise-start-inst", cl::Hidden, cl::value_desc("inst name"),
37 cl::desc("Start raise pass at the instruction with the specified name"));
40 NumLoadStorePeepholes("raise", "Number of load/store peepholes");
43 NumGEPInstFormed("raise", "Number of other getelementptr's formed");
46 NumExprTreesConv("raise", "Number of expression trees converted");
49 NumCastOfCast("raise", "Number of cast-of-self removed");
52 NumDCEorCP("raise", "Number of insts DCEd or constprop'd");
55 NumVarargCallChanges("raise", "Number of vararg call peepholes");
57 #define PRINT_PEEPHOLE(ID, NUM, I) \
58 DEBUG(std::cerr << "Inst P/H " << ID << "[" << NUM << "] " << I)
60 #define PRINT_PEEPHOLE1(ID, I1) do { PRINT_PEEPHOLE(ID, 0, I1); } while (0)
61 #define PRINT_PEEPHOLE2(ID, I1, I2) \
62 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); } while (0)
63 #define PRINT_PEEPHOLE3(ID, I1, I2, I3) \
64 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
65 PRINT_PEEPHOLE(ID, 2, I3); } while (0)
66 #define PRINT_PEEPHOLE4(ID, I1, I2, I3, I4) \
67 do { PRINT_PEEPHOLE(ID, 0, I1); PRINT_PEEPHOLE(ID, 1, I2); \
68 PRINT_PEEPHOLE(ID, 2, I3); PRINT_PEEPHOLE(ID, 3, I4); } while (0)
71 struct RPR : public FunctionPass {
72 virtual bool runOnFunction(Function &F);
74 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addRequired<TargetData>();
80 bool DoRaisePass(Function &F);
81 bool PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI);
84 RegisterOpt<RPR> X("raise", "Raise Pointer References");
88 Pass *llvm::createRaisePointerReferencesPass() {
93 // isReinterpretingCast - Return true if the cast instruction specified will
94 // cause the operand to be "reinterpreted". A value is reinterpreted if the
95 // cast instruction would cause the underlying bits to change.
97 static inline bool isReinterpretingCast(const CastInst *CI) {
98 return!CI->getOperand(0)->getType()->isLosslesslyConvertibleTo(CI->getType());
102 // Peephole optimize the following instructions:
103 // %t1 = cast ? to x *
104 // %t2 = add x * %SP, %t1 ;; Constant must be 2nd operand
106 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
107 // %t2 = cast <eltype> * %t3 to {<...>}*
109 static bool HandleCastToPointer(BasicBlock::iterator BI,
110 const PointerType *DestPTy,
111 const TargetData &TD) {
112 CastInst &CI = cast<CastInst>(*BI);
113 if (CI.use_empty()) return false;
115 // Scan all of the uses, looking for any uses that are not add or sub
116 // instructions. If we have non-adds, do not make this transformation.
118 bool HasSubUse = false; // Keep track of any subtracts...
119 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end();
121 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(*I)) {
122 if ((BO->getOpcode() != Instruction::Add &&
123 BO->getOpcode() != Instruction::Sub) ||
124 // Avoid add sbyte* %X, %X cases...
125 BO->getOperand(0) == BO->getOperand(1))
128 HasSubUse |= BO->getOpcode() == Instruction::Sub;
133 std::vector<Value*> Indices;
134 Value *Src = CI.getOperand(0);
135 const Type *Result = ConvertibleToGEP(DestPTy, Src, Indices, TD, &BI);
136 if (Result == 0) return false; // Not convertible...
138 // Cannot handle subtracts if there is more than one index required...
139 if (HasSubUse && Indices.size() != 1) return false;
141 PRINT_PEEPHOLE2("cast-add-to-gep:in", Src, CI);
143 // If we have a getelementptr capability... transform all of the
144 // add instruction uses into getelementptr's.
145 while (!CI.use_empty()) {
146 BinaryOperator *I = cast<BinaryOperator>(*CI.use_begin());
147 assert((I->getOpcode() == Instruction::Add ||
148 I->getOpcode() == Instruction::Sub) &&
149 "Use is not a valid add instruction!");
151 // Get the value added to the cast result pointer...
152 Value *OtherPtr = I->getOperand((I->getOperand(0) == &CI) ? 1 : 0);
154 Instruction *GEP = new GetElementPtrInst(OtherPtr, Indices, I->getName());
155 PRINT_PEEPHOLE1("cast-add-to-gep:i", I);
157 // If the instruction is actually a subtract, we are guaranteed to only have
158 // one index (from code above), so we just need to negate the pointer index
160 if (I->getOpcode() == Instruction::Sub) {
161 Instruction *Neg = BinaryOperator::createNeg(GEP->getOperand(1),
162 GEP->getOperand(1)->getName()+".neg", I);
163 GEP->setOperand(1, Neg);
166 if (GEP->getType() == I->getType()) {
167 // Replace the old add instruction with the shiny new GEP inst
168 ReplaceInstWithInst(I, GEP);
170 // If the type produced by the gep instruction differs from the original
171 // add instruction type, insert a cast now.
174 // Insert the GEP instruction before the old add instruction...
175 I->getParent()->getInstList().insert(I, GEP);
177 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
178 GEP = new CastInst(GEP, I->getType());
180 // Replace the old add instruction with the shiny new GEP inst
181 ReplaceInstWithInst(I, GEP);
184 PRINT_PEEPHOLE1("cast-add-to-gep:o", GEP);
189 // Peephole optimize the following instructions:
190 // %t1 = cast ulong <const int> to {<...>} *
191 // %t2 = add {<...>} * %SP, %t1 ;; Constant must be 2nd operand
194 // %t1 = cast {<...>}* %SP to int*
195 // %t5 = cast ulong <const int> to int*
196 // %t2 = add int* %t1, %t5 ;; int is same size as field
198 // Into: %t3 = getelementptr {<...>} * %SP, <element indices>
199 // %t2 = cast <eltype> * %t3 to {<...>}*
201 static bool PeepholeOptimizeAddCast(BasicBlock *BB, BasicBlock::iterator &BI,
202 Value *AddOp1, CastInst *AddOp2,
203 const TargetData &TD) {
204 const CompositeType *CompTy;
205 Value *OffsetVal = AddOp2->getOperand(0);
206 Value *SrcPtr = 0; // Of type pointer to struct...
208 if ((CompTy = getPointedToComposite(AddOp1->getType()))) {
209 SrcPtr = AddOp1; // Handle the first case...
210 } else if (CastInst *AddOp1c = dyn_cast<CastInst>(AddOp1)) {
211 SrcPtr = AddOp1c->getOperand(0); // Handle the second case...
212 CompTy = getPointedToComposite(SrcPtr->getType());
215 // Only proceed if we have detected all of our conditions successfully...
216 if (!CompTy || !SrcPtr || !OffsetVal->getType()->isInteger())
219 std::vector<Value*> Indices;
220 if (!ConvertibleToGEP(SrcPtr->getType(), OffsetVal, Indices, TD, &BI))
221 return false; // Not convertible... perhaps next time
223 if (getPointedToComposite(AddOp1->getType())) { // case 1
224 PRINT_PEEPHOLE2("add-to-gep1:in", AddOp2, *BI);
226 PRINT_PEEPHOLE3("add-to-gep2:in", AddOp1, AddOp2, *BI);
229 GetElementPtrInst *GEP = new GetElementPtrInst(SrcPtr, Indices,
230 AddOp2->getName(), BI);
232 Instruction *NCI = new CastInst(GEP, AddOp1->getType());
233 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
234 PRINT_PEEPHOLE2("add-to-gep:out", GEP, NCI);
238 bool RPR::PeepholeOptimize(BasicBlock *BB, BasicBlock::iterator &BI) {
240 const TargetData &TD = getAnalysis<TargetData>();
242 if (CastInst *CI = dyn_cast<CastInst>(I)) {
243 Value *Src = CI->getOperand(0);
244 Instruction *SrcI = dyn_cast<Instruction>(Src); // Nonnull if instr source
245 const Type *DestTy = CI->getType();
247 // Peephole optimize the following instruction:
248 // %V2 = cast <ty> %V to <ty>
252 if (DestTy == Src->getType()) { // Check for a cast to same type as src!!
253 PRINT_PEEPHOLE1("cast-of-self-ty", CI);
254 CI->replaceAllUsesWith(Src);
255 if (!Src->hasName() && CI->hasName()) {
256 std::string Name = CI->getName();
258 Src->setName(Name, &BB->getParent()->getSymbolTable());
261 // DCE the instruction now, to avoid having the iterative version of DCE
262 // have to worry about it.
264 BI = BB->getInstList().erase(BI);
270 // Check to see if it's a cast of an instruction that does not depend on the
271 // specific type of the operands to do it's job.
272 if (!isReinterpretingCast(CI)) {
273 ValueTypeCache ConvertedTypes;
275 // Check to see if we can convert the source of the cast to match the
276 // destination type of the cast...
278 ConvertedTypes[CI] = CI->getType(); // Make sure the cast doesn't change
279 if (ExpressionConvertibleToType(Src, DestTy, ConvertedTypes, TD)) {
280 PRINT_PEEPHOLE3("CAST-SRC-EXPR-CONV:in ", Src, CI, BB->getParent());
282 DEBUG(std::cerr << "\nCONVERTING SRC EXPR TYPE:\n");
283 { // ValueMap must be destroyed before function verified!
284 ValueMapCache ValueMap;
285 Value *E = ConvertExpressionToType(Src, DestTy, ValueMap, TD);
287 if (Constant *CPV = dyn_cast<Constant>(E))
288 CI->replaceAllUsesWith(CPV);
290 PRINT_PEEPHOLE1("CAST-SRC-EXPR-CONV:out", E);
291 DEBUG(std::cerr << "DONE CONVERTING SRC EXPR TYPE: \n"
295 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
300 // Check to see if we can convert the users of the cast value to match the
301 // source type of the cast...
303 ConvertedTypes.clear();
304 // Make sure the source doesn't change type
305 ConvertedTypes[Src] = Src->getType();
306 if (ValueConvertibleToType(CI, Src->getType(), ConvertedTypes, TD)) {
307 PRINT_PEEPHOLE3("CAST-DEST-EXPR-CONV:in ", Src, CI, BB->getParent());
309 DEBUG(std::cerr << "\nCONVERTING EXPR TYPE:\n");
310 { // ValueMap must be destroyed before function verified!
311 ValueMapCache ValueMap;
312 ConvertValueToNewType(CI, Src, ValueMap, TD); // This will delete CI!
315 PRINT_PEEPHOLE1("CAST-DEST-EXPR-CONV:out", Src);
316 DEBUG(std::cerr << "DONE CONVERTING EXPR TYPE: \n\n" << BB->getParent());
318 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
324 // Otherwise find out it this cast is a cast to a pointer type, which is
325 // then added to some other pointer, then loaded or stored through. If
326 // so, convert the add into a getelementptr instruction...
328 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
329 if (HandleCastToPointer(BI, DestPTy, TD)) {
330 BI = BB->begin(); // Rescan basic block. BI might be invalidated.
336 // Check to see if we are casting from a structure pointer to a pointer to
337 // the first element of the structure... to avoid munching other peepholes,
338 // we only let this happen if there are no add uses of the cast.
340 // Peephole optimize the following instructions:
341 // %t1 = cast {<...>} * %StructPtr to <ty> *
343 // Into: %t2 = getelementptr {<...>} * %StructPtr, <0, 0, 0, ...>
344 // %t1 = cast <eltype> * %t1 to <ty> *
346 if (const CompositeType *CTy = getPointedToComposite(Src->getType()))
347 if (const PointerType *DestPTy = dyn_cast<PointerType>(DestTy)) {
349 // Loop over uses of the cast, checking for add instructions. If an add
350 // exists, this is probably a part of a more complex GEP, so we don't
351 // want to mess around with the cast.
353 bool HasAddUse = false;
354 for (Value::use_iterator I = CI->use_begin(), E = CI->use_end();
356 if (isa<Instruction>(*I) &&
357 cast<Instruction>(*I)->getOpcode() == Instruction::Add) {
358 HasAddUse = true; break;
361 // If it doesn't have an add use, check to see if the dest type is
362 // losslessly convertible to one of the types in the start of the struct
366 const Type *DestPointedTy = DestPTy->getElementType();
368 const CompositeType *CurCTy = CTy;
369 const Type *ElTy = 0;
371 // Build the index vector, full of all zeros
372 std::vector<Value*> Indices;
373 Indices.push_back(ConstantSInt::get(Type::LongTy, 0));
374 while (CurCTy && !isa<PointerType>(CurCTy)) {
375 if (const StructType *CurSTy = dyn_cast<StructType>(CurCTy)) {
376 // Check for a zero element struct type... if we have one, bail.
377 if (CurSTy->getElementTypes().size() == 0) break;
379 // Grab the first element of the struct type, which must lie at
380 // offset zero in the struct.
382 ElTy = CurSTy->getElementTypes()[0];
384 ElTy = cast<ArrayType>(CurCTy)->getElementType();
387 // Insert a zero to index through this type...
388 Indices.push_back(Constant::getNullValue(CurCTy->getIndexType()));
390 // Did we find what we're looking for?
391 if (ElTy->isLosslesslyConvertibleTo(DestPointedTy)) break;
393 // Nope, go a level deeper.
395 CurCTy = dyn_cast<CompositeType>(ElTy);
399 // Did we find what we were looking for? If so, do the transformation
401 PRINT_PEEPHOLE1("cast-for-first:in", CI);
403 std::string Name = CI->getName(); CI->setName("");
405 // Insert the new T cast instruction... stealing old T's name
406 GetElementPtrInst *GEP = new GetElementPtrInst(Src, Indices,
409 // Make the old cast instruction reference the new GEP instead of
410 // the old src value.
412 CI->setOperand(0, GEP);
414 PRINT_PEEPHOLE2("cast-for-first:out", GEP, CI);
421 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
422 Value *Val = SI->getOperand(0);
423 Value *Pointer = SI->getPointerOperand();
425 // Peephole optimize the following instructions:
426 // %t = cast <T1>* %P to <T2> * ;; If T1 is losslessly convertible to T2
427 // store <T2> %V, <T2>* %t
430 // %t = cast <T2> %V to <T1>
431 // store <T1> %t2, <T1>* %P
433 // Note: This is not taken care of by expr conversion because there might
434 // not be a cast available for the store to convert the incoming value of.
435 // This code is basically here to make sure that pointers don't have casts
438 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
439 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
440 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
441 // convertible types?
442 if (Val->getType()->isLosslesslyConvertibleTo(CSPT->getElementType())) {
443 PRINT_PEEPHOLE3("st-src-cast:in ", Pointer, Val, SI);
445 // Insert the new T cast instruction... stealing old T's name
446 std::string Name(CI->getName()); CI->setName("");
447 CastInst *NCI = new CastInst(Val, CSPT->getElementType(),
450 // Replace the old store with a new one!
451 ReplaceInstWithInst(BB->getInstList(), BI,
452 SI = new StoreInst(NCI, CastSrc));
453 PRINT_PEEPHOLE3("st-src-cast:out", NCI, CastSrc, SI);
454 ++NumLoadStorePeepholes;
458 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
459 Value *Pointer = LI->getOperand(0);
460 const Type *PtrElType =
461 cast<PointerType>(Pointer->getType())->getElementType();
463 // Peephole optimize the following instructions:
464 // %Val = cast <T1>* to <T2>* ;; If T1 is losslessly convertible to T2
465 // %t = load <T2>* %P
468 // %t = load <T1>* %P
469 // %Val = cast <T1> to <T2>
471 // Note: This is not taken care of by expr conversion because there might
472 // not be a cast available for the store to convert the incoming value of.
473 // This code is basically here to make sure that pointers don't have casts
476 if (CastInst *CI = dyn_cast<CastInst>(Pointer))
477 if (Value *CastSrc = CI->getOperand(0)) // CSPT = CastSrcPointerType
478 if (const PointerType *CSPT = dyn_cast<PointerType>(CastSrc->getType()))
479 // convertible types?
480 if (PtrElType->isLosslesslyConvertibleTo(CSPT->getElementType())) {
481 PRINT_PEEPHOLE2("load-src-cast:in ", Pointer, LI);
483 // Create the new load instruction... loading the pre-casted value
484 LoadInst *NewLI = new LoadInst(CastSrc, LI->getName(), BI);
486 // Insert the new T cast instruction... stealing old T's name
487 CastInst *NCI = new CastInst(NewLI, LI->getType(), CI->getName());
489 // Replace the old store with a new one!
490 ReplaceInstWithInst(BB->getInstList(), BI, NCI);
491 PRINT_PEEPHOLE3("load-src-cast:out", NCI, CastSrc, NewLI);
492 ++NumLoadStorePeepholes;
496 } else if (I->getOpcode() == Instruction::Add &&
497 isa<CastInst>(I->getOperand(1))) {
499 if (PeepholeOptimizeAddCast(BB, BI, I->getOperand(0),
500 cast<CastInst>(I->getOperand(1)), TD)) {
504 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
505 // If we have a call with all varargs arguments, convert the call to use the
506 // actual argument types present...
508 const PointerType *PTy = cast<PointerType>(CI->getCalledValue()->getType());
509 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
511 // Is the call to a vararg variable with no real parameters?
512 if (FTy->isVarArg() && FTy->getNumParams() == 0 &&
513 !CI->getCalledFunction()) {
514 // If so, insert a new cast instruction, casting it to a function type
515 // that matches the current arguments...
517 std::vector<const Type *> Params; // Parameter types...
518 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
519 Params.push_back(CI->getOperand(i)->getType());
521 FunctionType *NewFT = FunctionType::get(FTy->getReturnType(),
523 PointerType *NewPFunTy = PointerType::get(NewFT);
525 // Create a new cast, inserting it right before the function call...
527 Constant *ConstantCallSrc = 0;
528 if (Constant *CS = dyn_cast<Constant>(CI->getCalledValue()))
529 ConstantCallSrc = CS;
530 else if (GlobalValue *GV = dyn_cast<GlobalValue>(CI->getCalledValue()))
531 ConstantCallSrc = ConstantPointerRef::get(GV);
534 NewCast = ConstantExpr::getCast(ConstantCallSrc, NewPFunTy);
536 NewCast = new CastInst(CI->getCalledValue(), NewPFunTy,
537 CI->getCalledValue()->getName()+"_c",CI);
539 // Create a new call instruction...
540 CallInst *NewCall = new CallInst(NewCast,
541 std::vector<Value*>(CI->op_begin()+1, CI->op_end()));
543 ReplaceInstWithInst(CI, NewCall);
545 ++NumVarargCallChanges;
557 bool RPR::DoRaisePass(Function &F) {
558 bool Changed = false;
559 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
560 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
561 DEBUG(std::cerr << "Processing: " << *BI);
562 if (dceInstruction(BI) || doConstantPropagation(BI)) {
565 DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
566 } else if (PeepholeOptimize(BB, BI)) {
577 // runOnFunction - Raise a function representation to a higher level.
578 bool RPR::runOnFunction(Function &F) {
579 DEBUG(std::cerr << "\n\n\nStarting to work on Function '" << F.getName()
582 // Insert casts for all incoming pointer pointer values that are treated as
585 bool Changed = false, LocalChange;
587 // If the StartInst option was specified, then Peephole optimize that
588 // instruction first if it occurs in this function.
590 if (!StartInst.empty()) {
591 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
592 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI)
593 if (BI->getName() == StartInst) {
594 bool SavedDebug = DebugFlag; // Save the DEBUG() controlling flag.
595 DebugFlag = true; // Turn on DEBUG's
596 Changed |= PeepholeOptimize(BB, BI);
597 DebugFlag = SavedDebug; // Restore DebugFlag to previous state
602 DEBUG(std::cerr << "Looping: \n" << F);
604 // Iterate over the function, refining it, until it converges on a stable
607 while (DoRaisePass(F)) LocalChange = true;
608 Changed |= LocalChange;
610 } while (LocalChange);