1 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the implementation of the scalar evolution expander,
11 // which is used to generate the code corresponding to a given scalar evolution
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Analysis/ScalarEvolutionExpander.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/ADT/STLExtras.h"
23 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
24 /// which must be possible with a noop cast, doing what we can to share
26 Value
*SCEVExpander::InsertNoopCastOfTo(Value
*V
, const Type
*Ty
) {
27 Instruction::CastOps Op
= CastInst::getCastOpcode(V
, false, Ty
, false);
28 assert((Op
== Instruction::BitCast
||
29 Op
== Instruction::PtrToInt
||
30 Op
== Instruction::IntToPtr
) &&
31 "InsertNoopCastOfTo cannot perform non-noop casts!");
32 assert(SE
.getTypeSizeInBits(V
->getType()) == SE
.getTypeSizeInBits(Ty
) &&
33 "InsertNoopCastOfTo cannot change sizes!");
35 // Short-circuit unnecessary bitcasts.
36 if (Op
== Instruction::BitCast
&& V
->getType() == Ty
)
39 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
40 if ((Op
== Instruction::PtrToInt
|| Op
== Instruction::IntToPtr
) &&
41 SE
.getTypeSizeInBits(Ty
) == SE
.getTypeSizeInBits(V
->getType())) {
42 if (CastInst
*CI
= dyn_cast
<CastInst
>(V
))
43 if ((CI
->getOpcode() == Instruction::PtrToInt
||
44 CI
->getOpcode() == Instruction::IntToPtr
) &&
45 SE
.getTypeSizeInBits(CI
->getType()) ==
46 SE
.getTypeSizeInBits(CI
->getOperand(0)->getType()))
47 return CI
->getOperand(0);
48 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(V
))
49 if ((CE
->getOpcode() == Instruction::PtrToInt
||
50 CE
->getOpcode() == Instruction::IntToPtr
) &&
51 SE
.getTypeSizeInBits(CE
->getType()) ==
52 SE
.getTypeSizeInBits(CE
->getOperand(0)->getType()))
53 return CE
->getOperand(0);
56 if (Constant
*C
= dyn_cast
<Constant
>(V
))
57 return ConstantExpr::getCast(Op
, C
, Ty
);
59 if (Argument
*A
= dyn_cast
<Argument
>(V
)) {
60 // Check to see if there is already a cast!
61 for (Value::use_iterator UI
= A
->use_begin(), E
= A
->use_end();
63 if ((*UI
)->getType() == Ty
)
64 if (CastInst
*CI
= dyn_cast
<CastInst
>(cast
<Instruction
>(*UI
)))
65 if (CI
->getOpcode() == Op
) {
66 // If the cast isn't the first instruction of the function, move it.
67 if (BasicBlock::iterator(CI
) !=
68 A
->getParent()->getEntryBlock().begin()) {
69 // Recreate the cast at the beginning of the entry block.
70 // The old cast is left in place in case it is being used
71 // as an insert point.
73 CastInst::Create(Op
, V
, Ty
, "",
74 A
->getParent()->getEntryBlock().begin());
76 CI
->replaceAllUsesWith(NewCI
);
82 Instruction
*I
= CastInst::Create(Op
, V
, Ty
, V
->getName(),
83 A
->getParent()->getEntryBlock().begin());
84 InsertedValues
.insert(I
);
88 Instruction
*I
= cast
<Instruction
>(V
);
90 // Check to see if there is already a cast. If there is, use it.
91 for (Value::use_iterator UI
= I
->use_begin(), E
= I
->use_end();
93 if ((*UI
)->getType() == Ty
)
94 if (CastInst
*CI
= dyn_cast
<CastInst
>(cast
<Instruction
>(*UI
)))
95 if (CI
->getOpcode() == Op
) {
96 BasicBlock::iterator It
= I
; ++It
;
97 if (isa
<InvokeInst
>(I
))
98 It
= cast
<InvokeInst
>(I
)->getNormalDest()->begin();
99 while (isa
<PHINode
>(It
)) ++It
;
100 if (It
!= BasicBlock::iterator(CI
)) {
101 // Recreate the cast at the beginning of the entry block.
102 // The old cast is left in place in case it is being used
103 // as an insert point.
104 Instruction
*NewCI
= CastInst::Create(Op
, V
, Ty
, "", It
);
106 CI
->replaceAllUsesWith(NewCI
);
112 BasicBlock::iterator IP
= I
; ++IP
;
113 if (InvokeInst
*II
= dyn_cast
<InvokeInst
>(I
))
114 IP
= II
->getNormalDest()->begin();
115 while (isa
<PHINode
>(IP
)) ++IP
;
116 Instruction
*CI
= CastInst::Create(Op
, V
, Ty
, V
->getName(), IP
);
117 InsertedValues
.insert(CI
);
121 /// InsertBinop - Insert the specified binary operator, doing a small amount
122 /// of work to avoid inserting an obviously redundant operation.
123 Value
*SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode
,
124 Value
*LHS
, Value
*RHS
) {
125 // Fold a binop with constant operands.
126 if (Constant
*CLHS
= dyn_cast
<Constant
>(LHS
))
127 if (Constant
*CRHS
= dyn_cast
<Constant
>(RHS
))
128 return ConstantExpr::get(Opcode
, CLHS
, CRHS
);
130 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
131 unsigned ScanLimit
= 6;
132 BasicBlock::iterator BlockBegin
= Builder
.GetInsertBlock()->begin();
133 // Scanning starts from the last instruction before the insertion point.
134 BasicBlock::iterator IP
= Builder
.GetInsertPoint();
135 if (IP
!= BlockBegin
) {
137 for (; ScanLimit
; --IP
, --ScanLimit
) {
138 if (IP
->getOpcode() == (unsigned)Opcode
&& IP
->getOperand(0) == LHS
&&
139 IP
->getOperand(1) == RHS
)
141 if (IP
== BlockBegin
) break;
145 // If we haven't found this binop, insert it.
146 Value
*BO
= Builder
.CreateBinOp(Opcode
, LHS
, RHS
, "tmp");
147 InsertedValues
.insert(BO
);
151 /// FactorOutConstant - Test if S is divisible by Factor, using signed
152 /// division. If so, update S with Factor divided out and return true.
153 /// S need not be evenly divisble if a reasonable remainder can be
155 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
156 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
157 /// check to see if the divide was folded.
158 static bool FactorOutConstant(const SCEV
*&S
,
159 const SCEV
*&Remainder
,
162 const TargetData
*TD
) {
163 // Everything is divisible by one.
169 S
= SE
.getIntegerSCEV(1, S
->getType());
173 // For a Constant, check for a multiple of the given factor.
174 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(S
)) {
178 // Check for divisibility.
179 if (const SCEVConstant
*FC
= dyn_cast
<SCEVConstant
>(Factor
)) {
181 ConstantInt::get(SE
.getContext(),
182 C
->getValue()->getValue().sdiv(
183 FC
->getValue()->getValue()));
184 // If the quotient is zero and the remainder is non-zero, reject
185 // the value at this scale. It will be considered for subsequent
188 const SCEV
*Div
= SE
.getConstant(CI
);
191 SE
.getAddExpr(Remainder
,
192 SE
.getConstant(C
->getValue()->getValue().srem(
193 FC
->getValue()->getValue())));
199 // In a Mul, check if there is a constant operand which is a multiple
200 // of the given factor.
201 if (const SCEVMulExpr
*M
= dyn_cast
<SCEVMulExpr
>(S
)) {
203 // With TargetData, the size is known. Check if there is a constant
204 // operand which is a multiple of the given factor. If so, we can
206 const SCEVConstant
*FC
= cast
<SCEVConstant
>(Factor
);
207 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(M
->getOperand(0)))
208 if (!C
->getValue()->getValue().srem(FC
->getValue()->getValue())) {
209 const SmallVectorImpl
<const SCEV
*> &MOperands
= M
->getOperands();
210 SmallVector
<const SCEV
*, 4> NewMulOps(MOperands
.begin(),
213 SE
.getConstant(C
->getValue()->getValue().sdiv(
214 FC
->getValue()->getValue()));
215 S
= SE
.getMulExpr(NewMulOps
);
219 // Without TargetData, check if Factor can be factored out of any of the
220 // Mul's operands. If so, we can just remove it.
221 for (unsigned i
= 0, e
= M
->getNumOperands(); i
!= e
; ++i
) {
222 const SCEV
*SOp
= M
->getOperand(i
);
223 const SCEV
*Remainder
= SE
.getIntegerSCEV(0, SOp
->getType());
224 if (FactorOutConstant(SOp
, Remainder
, Factor
, SE
, TD
) &&
225 Remainder
->isZero()) {
226 const SmallVectorImpl
<const SCEV
*> &MOperands
= M
->getOperands();
227 SmallVector
<const SCEV
*, 4> NewMulOps(MOperands
.begin(),
230 S
= SE
.getMulExpr(NewMulOps
);
237 // In an AddRec, check if both start and step are divisible.
238 if (const SCEVAddRecExpr
*A
= dyn_cast
<SCEVAddRecExpr
>(S
)) {
239 const SCEV
*Step
= A
->getStepRecurrence(SE
);
240 const SCEV
*StepRem
= SE
.getIntegerSCEV(0, Step
->getType());
241 if (!FactorOutConstant(Step
, StepRem
, Factor
, SE
, TD
))
243 if (!StepRem
->isZero())
245 const SCEV
*Start
= A
->getStart();
246 if (!FactorOutConstant(Start
, Remainder
, Factor
, SE
, TD
))
248 S
= SE
.getAddRecExpr(Start
, Step
, A
->getLoop());
255 /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
256 /// is the number of SCEVAddRecExprs present, which are kept at the end of
259 static void SimplifyAddOperands(SmallVectorImpl
<const SCEV
*> &Ops
,
261 ScalarEvolution
&SE
) {
262 unsigned NumAddRecs
= 0;
263 for (unsigned i
= Ops
.size(); i
> 0 && isa
<SCEVAddRecExpr
>(Ops
[i
-1]); --i
)
265 // Group Ops into non-addrecs and addrecs.
266 SmallVector
<const SCEV
*, 8> NoAddRecs(Ops
.begin(), Ops
.end() - NumAddRecs
);
267 SmallVector
<const SCEV
*, 8> AddRecs(Ops
.end() - NumAddRecs
, Ops
.end());
268 // Let ScalarEvolution sort and simplify the non-addrecs list.
269 const SCEV
*Sum
= NoAddRecs
.empty() ?
270 SE
.getIntegerSCEV(0, Ty
) :
271 SE
.getAddExpr(NoAddRecs
);
272 // If it returned an add, use the operands. Otherwise it simplified
273 // the sum into a single value, so just use that.
274 if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(Sum
))
275 Ops
= Add
->getOperands();
281 // Then append the addrecs.
282 Ops
.insert(Ops
.end(), AddRecs
.begin(), AddRecs
.end());
285 /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
286 /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
287 /// This helps expose more opportunities for folding parts of the expressions
288 /// into GEP indices.
290 static void SplitAddRecs(SmallVectorImpl
<const SCEV
*> &Ops
,
292 ScalarEvolution
&SE
) {
294 SmallVector
<const SCEV
*, 8> AddRecs
;
295 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
)
296 while (const SCEVAddRecExpr
*A
= dyn_cast
<SCEVAddRecExpr
>(Ops
[i
])) {
297 const SCEV
*Start
= A
->getStart();
298 if (Start
->isZero()) break;
299 const SCEV
*Zero
= SE
.getIntegerSCEV(0, Ty
);
300 AddRecs
.push_back(SE
.getAddRecExpr(Zero
,
301 A
->getStepRecurrence(SE
),
303 if (const SCEVAddExpr
*Add
= dyn_cast
<SCEVAddExpr
>(Start
)) {
305 Ops
.insert(Ops
.end(), Add
->op_begin(), Add
->op_end());
306 e
+= Add
->getNumOperands();
311 if (!AddRecs
.empty()) {
312 // Add the addrecs onto the end of the list.
313 Ops
.insert(Ops
.end(), AddRecs
.begin(), AddRecs
.end());
314 // Resort the operand list, moving any constants to the front.
315 SimplifyAddOperands(Ops
, Ty
, SE
);
319 /// expandAddToGEP - Expand an addition expression with a pointer type into
320 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
321 /// BasicAliasAnalysis and other passes analyze the result. See the rules
322 /// for getelementptr vs. inttoptr in
323 /// http://llvm.org/docs/LangRef.html#pointeraliasing
326 /// Design note: The correctness of using getelmeentptr here depends on
327 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
328 /// they may introduce pointer arithmetic which may not be safely converted
329 /// into getelementptr.
331 /// Design note: It might seem desirable for this function to be more
332 /// loop-aware. If some of the indices are loop-invariant while others
333 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
334 /// loop-invariant portions of the overall computation outside the loop.
335 /// However, there are a few reasons this is not done here. Hoisting simple
336 /// arithmetic is a low-level optimization that often isn't very
337 /// important until late in the optimization process. In fact, passes
338 /// like InstructionCombining will combine GEPs, even if it means
339 /// pushing loop-invariant computation down into loops, so even if the
340 /// GEPs were split here, the work would quickly be undone. The
341 /// LoopStrengthReduction pass, which is usually run quite late (and
342 /// after the last InstructionCombining pass), takes care of hoisting
343 /// loop-invariant portions of expressions, after considering what
344 /// can be folded using target addressing modes.
346 Value
*SCEVExpander::expandAddToGEP(const SCEV
*const *op_begin
,
347 const SCEV
*const *op_end
,
348 const PointerType
*PTy
,
351 const Type
*ElTy
= PTy
->getElementType();
352 SmallVector
<Value
*, 4> GepIndices
;
353 SmallVector
<const SCEV
*, 8> Ops(op_begin
, op_end
);
354 bool AnyNonZeroIndices
= false;
356 // Split AddRecs up into parts as either of the parts may be usable
357 // without the other.
358 SplitAddRecs(Ops
, Ty
, SE
);
360 // Decend down the pointer's type and attempt to convert the other
361 // operands into GEP indices, at each level. The first index in a GEP
362 // indexes into the array implied by the pointer operand; the rest of
363 // the indices index into the element or field type selected by the
366 const SCEV
*ElSize
= SE
.getAllocSizeExpr(ElTy
);
367 // If the scale size is not 0, attempt to factor out a scale for
369 SmallVector
<const SCEV
*, 8> ScaledOps
;
370 if (ElTy
->isSized() && !ElSize
->isZero()) {
371 SmallVector
<const SCEV
*, 8> NewOps
;
372 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
) {
373 const SCEV
*Op
= Ops
[i
];
374 const SCEV
*Remainder
= SE
.getIntegerSCEV(0, Ty
);
375 if (FactorOutConstant(Op
, Remainder
, ElSize
, SE
, SE
.TD
)) {
376 // Op now has ElSize factored out.
377 ScaledOps
.push_back(Op
);
378 if (!Remainder
->isZero())
379 NewOps
.push_back(Remainder
);
380 AnyNonZeroIndices
= true;
382 // The operand was not divisible, so add it to the list of operands
383 // we'll scan next iteration.
384 NewOps
.push_back(Ops
[i
]);
387 // If we made any changes, update Ops.
388 if (!ScaledOps
.empty()) {
390 SimplifyAddOperands(Ops
, Ty
, SE
);
394 // Record the scaled array index for this level of the type. If
395 // we didn't find any operands that could be factored, tentatively
396 // assume that element zero was selected (since the zero offset
397 // would obviously be folded away).
398 Value
*Scaled
= ScaledOps
.empty() ?
399 Constant::getNullValue(Ty
) :
400 expandCodeFor(SE
.getAddExpr(ScaledOps
), Ty
);
401 GepIndices
.push_back(Scaled
);
403 // Collect struct field index operands.
404 while (const StructType
*STy
= dyn_cast
<StructType
>(ElTy
)) {
405 bool FoundFieldNo
= false;
406 // An empty struct has no fields.
407 if (STy
->getNumElements() == 0) break;
409 // With TargetData, field offsets are known. See if a constant offset
410 // falls within any of the struct fields.
411 if (Ops
.empty()) break;
412 if (const SCEVConstant
*C
= dyn_cast
<SCEVConstant
>(Ops
[0]))
413 if (SE
.getTypeSizeInBits(C
->getType()) <= 64) {
414 const StructLayout
&SL
= *SE
.TD
->getStructLayout(STy
);
415 uint64_t FullOffset
= C
->getValue()->getZExtValue();
416 if (FullOffset
< SL
.getSizeInBytes()) {
417 unsigned ElIdx
= SL
.getElementContainingOffset(FullOffset
);
418 GepIndices
.push_back(
419 ConstantInt::get(Type::getInt32Ty(Ty
->getContext()), ElIdx
));
420 ElTy
= STy
->getTypeAtIndex(ElIdx
);
422 SE
.getConstant(Ty
, FullOffset
- SL
.getElementOffset(ElIdx
));
423 AnyNonZeroIndices
= true;
428 // Without TargetData, just check for a SCEVFieldOffsetExpr of the
429 // appropriate struct type.
430 for (unsigned i
= 0, e
= Ops
.size(); i
!= e
; ++i
)
431 if (const SCEVFieldOffsetExpr
*FO
=
432 dyn_cast
<SCEVFieldOffsetExpr
>(Ops
[i
]))
433 if (FO
->getStructType() == STy
) {
434 unsigned FieldNo
= FO
->getFieldNo();
435 GepIndices
.push_back(
436 ConstantInt::get(Type::getInt32Ty(Ty
->getContext()),
438 ElTy
= STy
->getTypeAtIndex(FieldNo
);
439 Ops
[i
] = SE
.getConstant(Ty
, 0);
440 AnyNonZeroIndices
= true;
445 // If no struct field offsets were found, tentatively assume that
446 // field zero was selected (since the zero offset would obviously
449 ElTy
= STy
->getTypeAtIndex(0u);
450 GepIndices
.push_back(
451 Constant::getNullValue(Type::getInt32Ty(Ty
->getContext())));
455 if (const ArrayType
*ATy
= dyn_cast
<ArrayType
>(ElTy
))
456 ElTy
= ATy
->getElementType();
461 // If none of the operands were convertable to proper GEP indices, cast
462 // the base to i8* and do an ugly getelementptr with that. It's still
463 // better than ptrtoint+arithmetic+inttoptr at least.
464 if (!AnyNonZeroIndices
) {
465 // Cast the base to i8*.
466 V
= InsertNoopCastOfTo(V
,
467 Type::getInt8Ty(Ty
->getContext())->getPointerTo(PTy
->getAddressSpace()));
469 // Expand the operands for a plain byte offset.
470 Value
*Idx
= expandCodeFor(SE
.getAddExpr(Ops
), Ty
);
472 // Fold a GEP with constant operands.
473 if (Constant
*CLHS
= dyn_cast
<Constant
>(V
))
474 if (Constant
*CRHS
= dyn_cast
<Constant
>(Idx
))
475 return ConstantExpr::getGetElementPtr(CLHS
, &CRHS
, 1);
477 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
478 unsigned ScanLimit
= 6;
479 BasicBlock::iterator BlockBegin
= Builder
.GetInsertBlock()->begin();
480 // Scanning starts from the last instruction before the insertion point.
481 BasicBlock::iterator IP
= Builder
.GetInsertPoint();
482 if (IP
!= BlockBegin
) {
484 for (; ScanLimit
; --IP
, --ScanLimit
) {
485 if (IP
->getOpcode() == Instruction::GetElementPtr
&&
486 IP
->getOperand(0) == V
&& IP
->getOperand(1) == Idx
)
488 if (IP
== BlockBegin
) break;
493 Value
*GEP
= Builder
.CreateGEP(V
, Idx
, "uglygep");
494 InsertedValues
.insert(GEP
);
498 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
499 // because ScalarEvolution may have changed the address arithmetic to
500 // compute a value which is beyond the end of the allocated object.
501 Value
*GEP
= Builder
.CreateGEP(V
,
505 Ops
.push_back(SE
.getUnknown(GEP
));
506 InsertedValues
.insert(GEP
);
507 return expand(SE
.getAddExpr(Ops
));
510 Value
*SCEVExpander::visitAddExpr(const SCEVAddExpr
*S
) {
511 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
512 Value
*V
= expand(S
->getOperand(S
->getNumOperands()-1));
514 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
515 // comments on expandAddToGEP for details.
516 if (const PointerType
*PTy
= dyn_cast
<PointerType
>(V
->getType())) {
517 const SmallVectorImpl
<const SCEV
*> &Ops
= S
->getOperands();
518 return expandAddToGEP(&Ops
[0], &Ops
[Ops
.size() - 1], PTy
, Ty
, V
);
521 V
= InsertNoopCastOfTo(V
, Ty
);
523 // Emit a bunch of add instructions
524 for (int i
= S
->getNumOperands()-2; i
>= 0; --i
) {
525 Value
*W
= expandCodeFor(S
->getOperand(i
), Ty
);
526 V
= InsertBinop(Instruction::Add
, V
, W
);
531 Value
*SCEVExpander::visitMulExpr(const SCEVMulExpr
*S
) {
532 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
533 int FirstOp
= 0; // Set if we should emit a subtract.
534 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(S
->getOperand(0)))
535 if (SC
->getValue()->isAllOnesValue())
538 int i
= S
->getNumOperands()-2;
539 Value
*V
= expandCodeFor(S
->getOperand(i
+1), Ty
);
541 // Emit a bunch of multiply instructions
542 for (; i
>= FirstOp
; --i
) {
543 Value
*W
= expandCodeFor(S
->getOperand(i
), Ty
);
544 V
= InsertBinop(Instruction::Mul
, V
, W
);
547 // -1 * ... ---> 0 - ...
549 V
= InsertBinop(Instruction::Sub
, Constant::getNullValue(Ty
), V
);
553 Value
*SCEVExpander::visitUDivExpr(const SCEVUDivExpr
*S
) {
554 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
556 Value
*LHS
= expandCodeFor(S
->getLHS(), Ty
);
557 if (const SCEVConstant
*SC
= dyn_cast
<SCEVConstant
>(S
->getRHS())) {
558 const APInt
&RHS
= SC
->getValue()->getValue();
559 if (RHS
.isPowerOf2())
560 return InsertBinop(Instruction::LShr
, LHS
,
561 ConstantInt::get(Ty
, RHS
.logBase2()));
564 Value
*RHS
= expandCodeFor(S
->getRHS(), Ty
);
565 return InsertBinop(Instruction::UDiv
, LHS
, RHS
);
568 /// Move parts of Base into Rest to leave Base with the minimal
569 /// expression that provides a pointer operand suitable for a
571 static void ExposePointerBase(const SCEV
*&Base
, const SCEV
*&Rest
,
572 ScalarEvolution
&SE
) {
573 while (const SCEVAddRecExpr
*A
= dyn_cast
<SCEVAddRecExpr
>(Base
)) {
574 Base
= A
->getStart();
575 Rest
= SE
.getAddExpr(Rest
,
576 SE
.getAddRecExpr(SE
.getIntegerSCEV(0, A
->getType()),
577 A
->getStepRecurrence(SE
),
580 if (const SCEVAddExpr
*A
= dyn_cast
<SCEVAddExpr
>(Base
)) {
581 Base
= A
->getOperand(A
->getNumOperands()-1);
582 SmallVector
<const SCEV
*, 8> NewAddOps(A
->op_begin(), A
->op_end());
583 NewAddOps
.back() = Rest
;
584 Rest
= SE
.getAddExpr(NewAddOps
);
585 ExposePointerBase(Base
, Rest
, SE
);
589 Value
*SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr
*S
) {
590 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
591 const Loop
*L
= S
->getLoop();
593 // First check for an existing canonical IV in a suitable type.
594 PHINode
*CanonicalIV
= 0;
595 if (PHINode
*PN
= L
->getCanonicalInductionVariable())
596 if (SE
.isSCEVable(PN
->getType()) &&
597 isa
<IntegerType
>(SE
.getEffectiveSCEVType(PN
->getType())) &&
598 SE
.getTypeSizeInBits(PN
->getType()) >= SE
.getTypeSizeInBits(Ty
))
601 // Rewrite an AddRec in terms of the canonical induction variable, if
602 // its type is more narrow.
604 SE
.getTypeSizeInBits(CanonicalIV
->getType()) >
605 SE
.getTypeSizeInBits(Ty
)) {
606 const SCEV
*Start
= SE
.getAnyExtendExpr(S
->getStart(),
607 CanonicalIV
->getType());
608 const SCEV
*Step
= SE
.getAnyExtendExpr(S
->getStepRecurrence(SE
),
609 CanonicalIV
->getType());
610 Value
*V
= expand(SE
.getAddRecExpr(Start
, Step
, S
->getLoop()));
611 BasicBlock
*SaveInsertBB
= Builder
.GetInsertBlock();
612 BasicBlock::iterator SaveInsertPt
= Builder
.GetInsertPoint();
613 BasicBlock::iterator NewInsertPt
=
614 next(BasicBlock::iterator(cast
<Instruction
>(V
)));
615 while (isa
<PHINode
>(NewInsertPt
)) ++NewInsertPt
;
616 V
= expandCodeFor(SE
.getTruncateExpr(SE
.getUnknown(V
), Ty
), 0,
618 Builder
.SetInsertPoint(SaveInsertBB
, SaveInsertPt
);
622 // {X,+,F} --> X + {0,+,F}
623 if (!S
->getStart()->isZero()) {
624 const SmallVectorImpl
<const SCEV
*> &SOperands
= S
->getOperands();
625 SmallVector
<const SCEV
*, 4> NewOps(SOperands
.begin(), SOperands
.end());
626 NewOps
[0] = SE
.getIntegerSCEV(0, Ty
);
627 const SCEV
*Rest
= SE
.getAddRecExpr(NewOps
, L
);
629 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
630 // comments on expandAddToGEP for details.
631 const SCEV
*Base
= S
->getStart();
632 const SCEV
*RestArray
[1] = { Rest
};
633 // Dig into the expression to find the pointer base for a GEP.
634 ExposePointerBase(Base
, RestArray
[0], SE
);
635 // If we found a pointer, expand the AddRec with a GEP.
636 if (const PointerType
*PTy
= dyn_cast
<PointerType
>(Base
->getType())) {
637 // Make sure the Base isn't something exotic, such as a multiplied
638 // or divided pointer value. In those cases, the result type isn't
639 // actually a pointer type.
640 if (!isa
<SCEVMulExpr
>(Base
) && !isa
<SCEVUDivExpr
>(Base
)) {
641 Value
*StartV
= expand(Base
);
642 assert(StartV
->getType() == PTy
&& "Pointer type mismatch for GEP!");
643 return expandAddToGEP(RestArray
, RestArray
+1, PTy
, Ty
, StartV
);
647 // Just do a normal add. Pre-expand the operands to suppress folding.
648 return expand(SE
.getAddExpr(SE
.getUnknown(expand(S
->getStart())),
649 SE
.getUnknown(expand(Rest
))));
652 // {0,+,1} --> Insert a canonical induction variable into the loop!
654 S
->getOperand(1) == SE
.getIntegerSCEV(1, Ty
)) {
655 // If there's a canonical IV, just use it.
657 assert(Ty
== SE
.getEffectiveSCEVType(CanonicalIV
->getType()) &&
658 "IVs with types different from the canonical IV should "
659 "already have been handled!");
663 // Create and insert the PHI node for the induction variable in the
665 BasicBlock
*Header
= L
->getHeader();
666 BasicBlock
*Preheader
= L
->getLoopPreheader();
667 PHINode
*PN
= PHINode::Create(Ty
, "indvar", Header
->begin());
668 InsertedValues
.insert(PN
);
669 PN
->addIncoming(Constant::getNullValue(Ty
), Preheader
);
671 pred_iterator HPI
= pred_begin(Header
);
672 assert(HPI
!= pred_end(Header
) && "Loop with zero preds???");
673 if (!L
->contains(*HPI
)) ++HPI
;
674 assert(HPI
!= pred_end(Header
) && L
->contains(*HPI
) &&
675 "No backedge in loop?");
677 // Insert a unit add instruction right before the terminator corresponding
679 Constant
*One
= ConstantInt::get(Ty
, 1);
680 Instruction
*Add
= BinaryOperator::CreateAdd(PN
, One
, "indvar.next",
681 (*HPI
)->getTerminator());
682 InsertedValues
.insert(Add
);
684 pred_iterator PI
= pred_begin(Header
);
685 if (*PI
== Preheader
)
687 PN
->addIncoming(Add
, *PI
);
691 // {0,+,F} --> {0,+,1} * F
692 // Get the canonical induction variable I for this loop.
693 Value
*I
= CanonicalIV
?
695 getOrInsertCanonicalInductionVariable(L
, Ty
);
697 // If this is a simple linear addrec, emit it now as a special case.
698 if (S
->isAffine()) // {0,+,F} --> i*F
700 expand(SE
.getTruncateOrNoop(
701 SE
.getMulExpr(SE
.getUnknown(I
),
702 SE
.getNoopOrAnyExtend(S
->getOperand(1),
706 // If this is a chain of recurrences, turn it into a closed form, using the
707 // folders, then expandCodeFor the closed form. This allows the folders to
708 // simplify the expression without having to build a bunch of special code
710 const SCEV
*IH
= SE
.getUnknown(I
); // Get I as a "symbolic" SCEV.
712 // Promote S up to the canonical IV type, if the cast is foldable.
713 const SCEV
*NewS
= S
;
714 const SCEV
*Ext
= SE
.getNoopOrAnyExtend(S
, I
->getType());
715 if (isa
<SCEVAddRecExpr
>(Ext
))
718 const SCEV
*V
= cast
<SCEVAddRecExpr
>(NewS
)->evaluateAtIteration(IH
, SE
);
719 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
721 // Truncate the result down to the original type, if needed.
722 const SCEV
*T
= SE
.getTruncateOrNoop(V
, Ty
);
726 Value
*SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr
*S
) {
727 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
728 Value
*V
= expandCodeFor(S
->getOperand(),
729 SE
.getEffectiveSCEVType(S
->getOperand()->getType()));
730 Value
*I
= Builder
.CreateTrunc(V
, Ty
, "tmp");
731 InsertedValues
.insert(I
);
735 Value
*SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr
*S
) {
736 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
737 Value
*V
= expandCodeFor(S
->getOperand(),
738 SE
.getEffectiveSCEVType(S
->getOperand()->getType()));
739 Value
*I
= Builder
.CreateZExt(V
, Ty
, "tmp");
740 InsertedValues
.insert(I
);
744 Value
*SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr
*S
) {
745 const Type
*Ty
= SE
.getEffectiveSCEVType(S
->getType());
746 Value
*V
= expandCodeFor(S
->getOperand(),
747 SE
.getEffectiveSCEVType(S
->getOperand()->getType()));
748 Value
*I
= Builder
.CreateSExt(V
, Ty
, "tmp");
749 InsertedValues
.insert(I
);
753 Value
*SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr
*S
) {
754 Value
*LHS
= expand(S
->getOperand(S
->getNumOperands()-1));
755 const Type
*Ty
= LHS
->getType();
756 for (int i
= S
->getNumOperands()-2; i
>= 0; --i
) {
757 // In the case of mixed integer and pointer types, do the
758 // rest of the comparisons as integer.
759 if (S
->getOperand(i
)->getType() != Ty
) {
760 Ty
= SE
.getEffectiveSCEVType(Ty
);
761 LHS
= InsertNoopCastOfTo(LHS
, Ty
);
763 Value
*RHS
= expandCodeFor(S
->getOperand(i
), Ty
);
764 Value
*ICmp
= Builder
.CreateICmpSGT(LHS
, RHS
, "tmp");
765 InsertedValues
.insert(ICmp
);
766 Value
*Sel
= Builder
.CreateSelect(ICmp
, LHS
, RHS
, "smax");
767 InsertedValues
.insert(Sel
);
770 // In the case of mixed integer and pointer types, cast the
771 // final result back to the pointer type.
772 if (LHS
->getType() != S
->getType())
773 LHS
= InsertNoopCastOfTo(LHS
, S
->getType());
777 Value
*SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr
*S
) {
778 Value
*LHS
= expand(S
->getOperand(S
->getNumOperands()-1));
779 const Type
*Ty
= LHS
->getType();
780 for (int i
= S
->getNumOperands()-2; i
>= 0; --i
) {
781 // In the case of mixed integer and pointer types, do the
782 // rest of the comparisons as integer.
783 if (S
->getOperand(i
)->getType() != Ty
) {
784 Ty
= SE
.getEffectiveSCEVType(Ty
);
785 LHS
= InsertNoopCastOfTo(LHS
, Ty
);
787 Value
*RHS
= expandCodeFor(S
->getOperand(i
), Ty
);
788 Value
*ICmp
= Builder
.CreateICmpUGT(LHS
, RHS
, "tmp");
789 InsertedValues
.insert(ICmp
);
790 Value
*Sel
= Builder
.CreateSelect(ICmp
, LHS
, RHS
, "umax");
791 InsertedValues
.insert(Sel
);
794 // In the case of mixed integer and pointer types, cast the
795 // final result back to the pointer type.
796 if (LHS
->getType() != S
->getType())
797 LHS
= InsertNoopCastOfTo(LHS
, S
->getType());
801 Value
*SCEVExpander::visitFieldOffsetExpr(const SCEVFieldOffsetExpr
*S
) {
802 return ConstantExpr::getOffsetOf(S
->getStructType(), S
->getFieldNo());
805 Value
*SCEVExpander::visitAllocSizeExpr(const SCEVAllocSizeExpr
*S
) {
806 return ConstantExpr::getSizeOf(S
->getAllocType());
809 Value
*SCEVExpander::expandCodeFor(const SCEV
*SH
, const Type
*Ty
) {
810 // Expand the code for this SCEV.
811 Value
*V
= expand(SH
);
813 assert(SE
.getTypeSizeInBits(Ty
) == SE
.getTypeSizeInBits(SH
->getType()) &&
814 "non-trivial casts should be done with the SCEVs directly!");
815 V
= InsertNoopCastOfTo(V
, Ty
);
820 Value
*SCEVExpander::expand(const SCEV
*S
) {
821 // Compute an insertion point for this SCEV object. Hoist the instructions
822 // as far out in the loop nest as possible.
823 Instruction
*InsertPt
= Builder
.GetInsertPoint();
824 for (Loop
*L
= SE
.LI
->getLoopFor(Builder
.GetInsertBlock()); ;
825 L
= L
->getParentLoop())
826 if (S
->isLoopInvariant(L
)) {
828 if (BasicBlock
*Preheader
= L
->getLoopPreheader())
829 InsertPt
= Preheader
->getTerminator();
831 // If the SCEV is computable at this level, insert it into the header
832 // after the PHIs (and after any other instructions that we've inserted
833 // there) so that it is guaranteed to dominate any user inside the loop.
834 if (L
&& S
->hasComputableLoopEvolution(L
))
835 InsertPt
= L
->getHeader()->getFirstNonPHI();
836 while (isInsertedInstruction(InsertPt
))
837 InsertPt
= next(BasicBlock::iterator(InsertPt
));
841 // Check to see if we already expanded this here.
842 std::map
<std::pair
<const SCEV
*, Instruction
*>,
843 AssertingVH
<Value
> >::iterator I
=
844 InsertedExpressions
.find(std::make_pair(S
, InsertPt
));
845 if (I
!= InsertedExpressions
.end())
848 BasicBlock
*SaveInsertBB
= Builder
.GetInsertBlock();
849 BasicBlock::iterator SaveInsertPt
= Builder
.GetInsertPoint();
850 Builder
.SetInsertPoint(InsertPt
->getParent(), InsertPt
);
852 // Expand the expression into instructions.
855 // Remember the expanded value for this SCEV at this location.
856 InsertedExpressions
[std::make_pair(S
, InsertPt
)] = V
;
858 Builder
.SetInsertPoint(SaveInsertBB
, SaveInsertPt
);
862 /// getOrInsertCanonicalInductionVariable - This method returns the
863 /// canonical induction variable of the specified type for the specified
864 /// loop (inserting one if there is none). A canonical induction variable
865 /// starts at zero and steps by one on each iteration.
867 SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop
*L
,
869 assert(Ty
->isInteger() && "Can only insert integer induction variables!");
870 const SCEV
*H
= SE
.getAddRecExpr(SE
.getIntegerSCEV(0, Ty
),
871 SE
.getIntegerSCEV(1, Ty
), L
);
872 BasicBlock
*SaveInsertBB
= Builder
.GetInsertBlock();
873 BasicBlock::iterator SaveInsertPt
= Builder
.GetInsertPoint();
874 Value
*V
= expandCodeFor(H
, 0, L
->getHeader()->begin());
876 Builder
.SetInsertPoint(SaveInsertBB
, SaveInsertPt
);