aboutsummaryrefslogtreecommitdiff
path: root/lib/Transforms/Scalar/IndVarSimplify.cpp
blob: ed02e3a00bb9fd26d72eb92f843de3295b0f0699 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
// 
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
// 
//===----------------------------------------------------------------------===//
//
// Guarantees that all loops with identifiable, linear, induction variables will
// be transformed to have a single, canonical, induction variable.  After this
// pass runs, it guarantees the the first PHI node of the header block in the
// loop is the canonical induction variable if there is one.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "indvar"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/Instructions.h"
#include "llvm/Analysis/InductionVariable.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Support/CFG.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/Utils/Local.h"
#include "Support/Debug.h"
#include "Support/Statistic.h"
using namespace llvm;

namespace {
  Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
  Statistic<> NumInserted("indvars", "Number of canonical indvars added");

  class IndVarSimplify : public FunctionPass {
    LoopInfo *Loops;
    TargetData *TD;
    bool Changed;
  public:
    virtual bool runOnFunction(Function &) {
      Loops = &getAnalysis<LoopInfo>();
      TD = &getAnalysis<TargetData>();
      Changed = false;

      // Induction Variables live in the header nodes of loops
      for (unsigned i = 0, e = Loops->getTopLevelLoops().size(); i != e; ++i)
        runOnLoop(Loops->getTopLevelLoops()[i]);
      return Changed;
    }

    unsigned getTypeSize(const Type *Ty) {
      if (unsigned Size = Ty->getPrimitiveSize())
        return Size;
      return TD->getTypeSize(Ty);  // Must be a pointer
    }

    Value *ComputeAuxIndVarValue(InductionVariable &IV, Value *CIV);  
    void ReplaceIndVar(InductionVariable &IV, Value *Counter);

    void runOnLoop(Loop *L);

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.addRequired<TargetData>();   // Need pointer size
      AU.addRequired<LoopInfo>();
      AU.addRequiredID(LoopSimplifyID);
      AU.addPreservedID(LoopSimplifyID);
      AU.setPreservesCFG();
    }
  };
  RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
}

Pass *llvm::createIndVarSimplifyPass() {
  return new IndVarSimplify();
}


void IndVarSimplify::runOnLoop(Loop *Loop) {
  // Transform all subloops before this loop...
  for (unsigned i = 0, e = Loop->getSubLoops().size(); i != e; ++i)
    runOnLoop(Loop->getSubLoops()[i]);

  // Get the header node for this loop.  All of the phi nodes that could be
  // induction variables must live in this basic block.
  //
  BasicBlock *Header = Loop->getHeader();
  
  // Loop over all of the PHI nodes in the basic block, calculating the
  // induction variables that they represent... stuffing the induction variable
  // info into a vector...
  //
  std::vector<InductionVariable> IndVars;    // Induction variables for block
  BasicBlock::iterator AfterPHIIt = Header->begin();
  for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt)
    IndVars.push_back(InductionVariable(PN, Loops));
  // AfterPHIIt now points to first non-phi instruction...

  // If there are no phi nodes in this basic block, there can't be indvars...
  if (IndVars.empty()) return;
  
  // Loop over the induction variables, looking for a canonical induction
  // variable, and checking to make sure they are not all unknown induction
  // variables.  Keep track of the largest integer size of the induction
  // variable.
  //
  InductionVariable *Canonical = 0;
  unsigned MaxSize = 0;

  for (unsigned i = 0; i != IndVars.size(); ++i) {
    InductionVariable &IV = IndVars[i];

    if (IV.InductionType != InductionVariable::Unknown) {
      unsigned IVSize = getTypeSize(IV.Phi->getType());

      if (IV.InductionType == InductionVariable::Canonical &&
          !isa<PointerType>(IV.Phi->getType()) && IVSize >= MaxSize)
        Canonical = &IV;
      
      if (IVSize > MaxSize) MaxSize = IVSize;

      // If this variable is larger than the currently identified canonical
      // indvar, the canonical indvar is not usable.
      if (Canonical && IVSize > getTypeSize(Canonical->Phi->getType()))
        Canonical = 0;
    }
  }

  // No induction variables, bail early... don't add a canonical indvar
  if (MaxSize == 0) return;


  // Figure out what the exit condition of the loop is.  We can currently only
  // handle loops with a single exit.  If we cannot figure out what the
  // termination condition is, we leave this variable set to null.
  //
  SetCondInst *TermCond = 0;
  if (Loop->getExitBlocks().size() == 1) {
    // Get ExitingBlock - the basic block in the loop which contains the branch
    // out of the loop.
    BasicBlock *Exit = Loop->getExitBlocks()[0];
    pred_iterator PI = pred_begin(Exit);
    assert(PI != pred_end(Exit) && "Should have one predecessor in loop!");
    BasicBlock *ExitingBlock = *PI;
    assert(++PI == pred_end(Exit) && "Exit block should have one pred!");
    assert(Loop->isLoopExit(ExitingBlock) && "Exiting block is not loop exit!");

    // Since the block is in the loop, yet branches out of it, we know that the
    // block must end with multiple destination terminator.  Which means it is
    // either a conditional branch, a switch instruction, or an invoke.
    if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
      assert(BI->isConditional() && "Unconditional branch has multiple succs?");
      TermCond = dyn_cast<SetCondInst>(BI->getCondition());
    } else {
      // NOTE: if people actually exit loops with switch instructions, we could
      // handle them, but I don't think this is important enough to spend time
      // thinking about.
      assert(isa<SwitchInst>(ExitingBlock->getTerminator()) ||
             isa<InvokeInst>(ExitingBlock->getTerminator()) &&
             "Unknown multi-successor terminator!");
    }
  }

  if (TermCond)
    DEBUG(std::cerr << "INDVAR: Found termination condition: " << *TermCond);

  // Okay, we want to convert other induction variables to use a canonical
  // indvar.  If we don't have one, add one now...
  if (!Canonical) {
    // Create the PHI node for the new induction variable, and insert the phi
    // node at the start of the PHI nodes...
    const Type *IVType;
    switch (MaxSize) {
    default: assert(0 && "Unknown integer type size!");
    case 1: IVType = Type::UByteTy; break;
    case 2: IVType = Type::UShortTy; break;
    case 4: IVType = Type::UIntTy; break;
    case 8: IVType = Type::ULongTy; break;
    }
    
    PHINode *PN = new PHINode(IVType, "cann-indvar", Header->begin());

    // Create the increment instruction to add one to the counter...
    Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
                                              ConstantUInt::get(IVType, 1),
                                              "next-indvar", AfterPHIIt);

    // Figure out which block is incoming and which is the backedge for the loop
    BasicBlock *Incoming, *BackEdgeBlock;
    pred_iterator PI = pred_begin(Header);
    assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
    if (Loop->contains(*PI)) {  // First pred is back edge...
      BackEdgeBlock = *PI++;
      Incoming      = *PI++;
    } else {
      Incoming      = *PI++;
      BackEdgeBlock = *PI++;
    }
    assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
    
    // Add incoming values for the PHI node...
    PN->addIncoming(Constant::getNullValue(IVType), Incoming);
    PN->addIncoming(Add, BackEdgeBlock);

    // Analyze the new induction variable...
    IndVars.push_back(InductionVariable(PN, Loops));
    assert(IndVars.back().InductionType == InductionVariable::Canonical &&
           "Just inserted canonical indvar that is not canonical!");
    Canonical = &IndVars.back();
    ++NumInserted;
    Changed = true;
    DEBUG(std::cerr << "INDVAR: Inserted canonical iv: " << *PN);
  } else {
    // If we have a canonical induction variable, make sure that it is the first
    // one in the basic block.
    if (&Header->front() != Canonical->Phi)
      Header->getInstList().splice(Header->begin(), Header->getInstList(),
                                   Canonical->Phi);
    DEBUG(std::cerr << "IndVar: Existing canonical iv used: "
                    << *Canonical->Phi);