Moved all of the cilkifier stuff into lib/Transforms/IPO, as it really is not
[oota-llvm.git] / lib / Transforms / IPO / Parallelize.cpp
1 //===- Parallelize.cpp - Auto parallelization using DS Graphs -------------===//
2 //
3 // This file implements a pass that automatically parallelizes a program,
4 // using the Cilk multi-threaded runtime system to execute parallel code.
5 // 
6 // The pass uses the Program Dependence Graph (class PDGIterator) to
7 // identify parallelizable function calls, i.e., calls whose instances
8 // can be executed in parallel with instances of other function calls.
9 // (In the future, this should also execute different instances of the same
10 // function call in parallel, but that requires parallelizing across
11 // loop iterations.)
12 //
13 // The output of the pass is LLVM code with:
14 // (1) all parallelizable functions renamed to flag them as parallelizable;
15 // (2) calls to a sync() function introduced at synchronization points.
16 // The CWriter recognizes these functions and inserts the appropriate Cilk
17 // keywords when writing out C code.  This C code must be compiled with cilk2c.
18 // 
19 // Current algorithmic limitations:
20 // -- no array dependence analysis
21 // -- no parallelization for function calls in different loop iterations
22 //    (except in unlikely trivial cases)
23 //
24 // Limitations of using Cilk:
25 // -- No parallelism within a function body, e.g., in a loop;
26 // -- Simplistic synchronization model requiring all parallel threads 
27 //    created within a function to block at a sync().
28 // -- Excessive overhead at "spawned" function calls, which has no benefit
29 //    once all threads are busy (especially common when the degree of
30 //    parallelism is low).
31 //
32 //===----------------------------------------------------------------------===//
33
34 #include "Cilkifier.h"
35 #include "llvm/Transforms/Utils/DemoteRegToStack.h"
36 #include "llvm/Analysis/PgmDependenceGraph.h"
37 #include "llvm/Analysis/Dominators.h"
38 #include "llvm/Analysis/DataStructure.h"
39 #include "llvm/Analysis/DSGraph.h"
40 #include "llvm/Module.h"
41 #include "llvm/Instructions.h"
42 #include "llvm/iTerminators.h"
43 #include "llvm/DerivedTypes.h"
44 #include "llvm/Support/InstVisitor.h"
45 #include "Support/Statistic.h"
46 #include "Support/STLExtras.h"
47 #include "Support/hash_set"
48 #include "Support/hash_map"
49 #include <functional>
50 #include <algorithm>
51
52
53
54 #if 0
55 void AddToDomSet(vector<BasicBlock*>& domSet, BasicBlock* bb,
56                  const DominatorTree& domTree)
57 {
58   DominatorTreeBase::Node* bbNode = domTree.getNode(bb);
59   const std::vector<Node*>& domKids = bbNode.getChildren();
60   domSet.insert(domSet.end(), domKids.begin(), domKids.end());
61   for (unsigned i = 0; i < domKids.size(); ++i)
62     AddToDomSet(domSet, domKids[i]->getNode(), domTree);
63 }
64
65 bool CheckDominance(Function& func,
66                     const CallInst& callInst1,
67                     const CallInst& callInst2)
68 {
69   if (callInst1 == callInst2)           // makes sense if this is in a loop but
70     return false;                       // we're not handling loops yet
71
72   // Check first if one call dominates the other
73   DominatorSet& domSet = getAnalysis<DominatorSet>(func);
74   if (domSet.dominates(callInst2, callInst1))
75     { // swap callInst1 and callInst2
76       const CallInst& tmp = callInst2; callInst2 = callInst1; callInst1 = tmp;
77     }
78   else if (! domSet.dominates(callInst1, callInst2))
79     return false;                       // neither dominates the other: 
80
81   // 
82   if (! AreIndependent(func, callInst1, callInst2))
83     return false;
84 }
85
86 #endif
87
88
89 //---------------------------------------------------------------------------- 
90 // class Cilkifier
91 //
92 // Code generation pass that transforms code to identify where Cilk keywords
93 // should be inserted.  This relies on dis -c to print out the keywords.
94 //---------------------------------------------------------------------------- 
95
96
97 class Cilkifier: public InstVisitor<Cilkifier>
98 {
99   Function* DummySyncFunc;
100
101   // Data used when transforming each function.
102   hash_set<const Instruction*>  stmtsVisited;    // Flags for recursive DFS
103   hash_map<const CallInst*, hash_set<CallInst*> > spawnToSyncsMap;
104
105   // Input data for the transformation.
106   const hash_set<Function*>*    cilkFunctions;   // Set of parallel functions
107   PgmDependenceGraph*           depGraph;
108
109   void          DFSVisitInstr   (Instruction* I,
110                                  Instruction* root,
111                                  hash_set<const Instruction*>& depsOfRoot);
112
113 public:
114   /*ctor*/      Cilkifier       (Module& M);
115
116   // Transform a single function including its name, its call sites, and syncs
117   // 
118   void          TransformFunc   (Function* F,
119                                  const hash_set<Function*>& cilkFunctions,
120                                  PgmDependenceGraph&  _depGraph);
121
122   // The visitor function that does most of the hard work, via DFSVisitInstr
123   // 
124   void visitCallInst(CallInst& CI);
125 };
126
127
128 Cilkifier::Cilkifier(Module& M)
129 {
130   // create the dummy Sync function and add it to the Module
131   DummySyncFunc = new Function(FunctionType::get( Type::VoidTy,
132                                                  std::vector<const Type*>(),
133                                                  /*isVararg*/ false),
134                                GlobalValue::ExternalLinkage, DummySyncFuncName,
135                                &M);
136 }
137
138 void Cilkifier::TransformFunc(Function* F,
139                               const hash_set<Function*>& _cilkFunctions,
140                               PgmDependenceGraph& _depGraph)
141 {
142   // Memoize the information for this function
143   cilkFunctions = &_cilkFunctions;
144   depGraph = &_depGraph;
145
146   // Add the marker suffix to the Function name
147   // This should automatically mark all calls to the function also!
148   F->setName(F->getName() + CilkSuffix);
149
150   // Insert sync operations for each separate spawn
151   visit(*F);
152
153   // Now traverse the CFG in rPostorder and eliminate redundant syncs, i.e.,
154   // two consecutive sync's on a straight-line path with no intervening spawn.
155   
156 }
157
158
159 void Cilkifier::DFSVisitInstr(Instruction* I,
160                               Instruction* root,
161                               hash_set<const Instruction*>& depsOfRoot)
162 {
163   assert(stmtsVisited.find(I) == stmtsVisited.end());
164   stmtsVisited.insert(I);
165
166   // If there is a dependence from root to I, insert Sync and return
167   if (depsOfRoot.find(I) != depsOfRoot.end())
168     { // Insert a sync before I and stop searching along this path.
169       // If I is a Phi instruction, the dependence can only be an SSA dep.
170       // and we need to insert the sync in the predecessor on the appropriate
171       // incoming edge!
172       CallInst* syncI = 0;
173       if (PHINode* phiI = dyn_cast<PHINode>(I))
174         { // check all operands of the Phi and insert before each one
175           for (unsigned i = 0, N = phiI->getNumIncomingValues(); i < N; ++i)
176             if (phiI->getIncomingValue(i) == root)
177               syncI = new CallInst(DummySyncFunc, std::vector<Value*>(), "",
178                                    phiI->getIncomingBlock(i)->getTerminator());
179         }
180       else
181         syncI = new CallInst(DummySyncFunc, std::vector<Value*>(), "", I);
182
183       // Remember the sync for each spawn to eliminate rendundant ones later
184       spawnToSyncsMap[cast<CallInst>(root)].insert(syncI);
185
186       return;
187     }
188
189   // else visit unvisited successors
190   if (BranchInst* brI = dyn_cast<BranchInst>(I))
191     { // visit first instruction in each successor BB
192       for (unsigned i = 0, N = brI->getNumSuccessors(); i < N; ++i)
193         if (stmtsVisited.find(&brI->getSuccessor(i)->front())
194             == stmtsVisited.end())
195           DFSVisitInstr(&brI->getSuccessor(i)->front(), root, depsOfRoot);
196     }
197   else
198     if (Instruction* nextI = I->getNext())
199       if (stmtsVisited.find(nextI) == stmtsVisited.end())
200         DFSVisitInstr(nextI, root, depsOfRoot);
201 }
202
203
204 void Cilkifier::visitCallInst(CallInst& CI)
205 {
206   assert(CI.getCalledFunction() != 0 && "Only direct calls can be spawned.");
207   if (cilkFunctions->find(CI.getCalledFunction()) == cilkFunctions->end())
208     return;                             // not a spawn
209
210   // Find all the outgoing memory dependences.
211   hash_set<const Instruction*> depsOfRoot;
212   for (PgmDependenceGraph::iterator DI =
213          depGraph->outDepBegin(CI, MemoryDeps); ! DI.fini(); ++DI)
214     depsOfRoot.insert(&DI->getSink()->getInstr());
215
216   // Now find all outgoing SSA dependences to the eventual non-Phi users of
217   // the call value (i.e., direct users that are not phis, and for any
218   // user that is a Phi, direct non-Phi users of that Phi, and recursively).
219   std::vector<const PHINode*> phiUsers;
220   hash_set<const PHINode*> phisSeen;    // ensures we don't visit a phi twice
221   for (Value::use_iterator UI=CI.use_begin(), UE=CI.use_end(); UI != UE; ++UI)
222     if (const PHINode* phiUser = dyn_cast<PHINode>(*UI))
223       {
224         if (phisSeen.find(phiUser) == phisSeen.end())
225           {
226             phiUsers.push_back(phiUser);
227             phisSeen.insert(phiUser);
228           }
229       }
230     else
231       depsOfRoot.insert(cast<Instruction>(*UI));
232
233   // Now we've found the non-Phi users and immediate phi users.
234   // Recursively walk the phi users and add their non-phi users.
235   for (const PHINode* phiUser; !phiUsers.empty(); phiUsers.pop_back())
236     {
237       phiUser = phiUsers.back();
238       for (Value::use_const_iterator UI=phiUser->use_begin(),
239              UE=phiUser->use_end(); UI != UE; ++UI)
240         if (const PHINode* pn = dyn_cast<PHINode>(*UI))
241           {
242             if (phisSeen.find(pn) == phisSeen.end())
243               {
244                 phiUsers.push_back(pn);
245                 phisSeen.insert(pn);
246               }
247           }
248         else
249           depsOfRoot.insert(cast<Instruction>(*UI));
250     }
251
252   // Walk paths of the CFG starting at the call instruction and insert
253   // one sync before the first dependence on each path, if any.
254   if (! depsOfRoot.empty())
255     {
256       stmtsVisited.clear();             // start a new DFS for this CallInst
257       assert(CI.getNext() && "Call instruction cannot be a terminator!");
258       DFSVisitInstr(CI.getNext(), &CI, depsOfRoot);
259     }
260
261   // Now, eliminate all users of the SSA value of the CallInst, i.e., 
262   // if the call instruction returns a value, delete the return value
263   // register and replace it by a stack slot.
264   if (CI.getType() != Type::VoidTy)
265     DemoteRegToStack(CI);
266 }
267
268
269 //---------------------------------------------------------------------------- 
270 // class FindParallelCalls
271 //
272 // Find all CallInst instructions that have at least one other CallInst
273 // that is independent.  These are the instructions that can produce
274 // useful parallelism.
275 //---------------------------------------------------------------------------- 
276
277 class FindParallelCalls : public InstVisitor<FindParallelCalls> {
278   typedef hash_set<CallInst*>           DependentsSet;
279   typedef DependentsSet::iterator       Dependents_iterator;
280   typedef DependentsSet::const_iterator Dependents_const_iterator;
281
282   PgmDependenceGraph& depGraph;         // dependence graph for the function
283   hash_set<Instruction*> stmtsVisited;  // flags for DFS walk of depGraph
284   hash_map<CallInst*, bool > completed; // flags marking if a CI is done
285   hash_map<CallInst*, DependentsSet> dependents; // dependent CIs for each CI
286
287   void VisitOutEdges(Instruction*   I,
288                      CallInst*      root,
289                      DependentsSet& depsOfRoot);
290
291   FindParallelCalls(const FindParallelCalls &); // DO NOT IMPLEMENT
292   void operator=(const FindParallelCalls&);     // DO NOT IMPLEMENT
293 public:
294   std::vector<CallInst*> parallelCalls;
295
296 public:
297   /*ctor*/      FindParallelCalls       (Function& F, PgmDependenceGraph& DG);
298   void          visitCallInst           (CallInst& CI);
299 };
300
301
302 FindParallelCalls::FindParallelCalls(Function& F,
303                                      PgmDependenceGraph& DG)
304   : depGraph(DG)
305 {
306   // Find all CallInsts reachable from each CallInst using a recursive DFS
307   visit(F);
308
309   // Now we've found all CallInsts reachable from each CallInst.
310   // Find those CallInsts that are parallel with at least one other CallInst
311   // by counting total inEdges and outEdges.
312   // 
313   unsigned long totalNumCalls = completed.size();
314
315   if (totalNumCalls == 1)
316     { // Check first for the special case of a single call instruction not
317       // in any loop.  It is not parallel, even if it has no dependences
318       // (this is why it is a special case).
319       //
320       // FIXME:
321       // THIS CASE IS NOT HANDLED RIGHT NOW, I.E., THERE IS NO
322       // PARALLELISM FOR CALLS IN DIFFERENT ITERATIONS OF A LOOP.
323       // 
324       return;
325     }
326
327   hash_map<CallInst*, unsigned long> numDeps;
328   for (hash_map<CallInst*, DependentsSet>::iterator II = dependents.begin(),
329          IE = dependents.end(); II != IE; ++II)
330     {
331       CallInst* fromCI = II->first;
332       numDeps[fromCI] += II->second.size();
333       for (Dependents_iterator DI = II->second.begin(), DE = II->second.end();
334            DI != DE; ++DI)
335         numDeps[*DI]++;                 // *DI can be reached from II->first
336     }
337
338   for (hash_map<CallInst*, DependentsSet>::iterator
339          II = dependents.begin(), IE = dependents.end(); II != IE; ++II)
340
341     // FIXME: Remove "- 1" when considering parallelism in loops
342     if (numDeps[II->first] < totalNumCalls - 1)
343       parallelCalls.push_back(II->first);
344 }
345
346
347 void FindParallelCalls::VisitOutEdges(Instruction* I,
348                                       CallInst* root,
349                                       DependentsSet& depsOfRoot)
350 {
351   assert(stmtsVisited.find(I) == stmtsVisited.end() && "Stmt visited twice?");
352   stmtsVisited.insert(I);
353
354   if (CallInst* CI = dyn_cast<CallInst>(I))
355
356     // FIXME: Ignoring parallelism in a loop.  Here we're actually *ignoring*
357     // a self-dependence in order to get the count comparison right above.
358     // When we include loop parallelism, self-dependences should be included.
359     // 
360     if (CI != root)
361
362       { // CallInst root has a path to CallInst I and any calls reachable from I
363         depsOfRoot.insert(CI);
364         if (completed[CI])
365           { // We have already visited I so we know all nodes it can reach!
366             DependentsSet& depsOfI = dependents[CI];
367             depsOfRoot.insert(depsOfI.begin(), depsOfI.end());
368             return;
369           }
370       }
371
372   // If we reach here, we need to visit all children of I
373   for (PgmDependenceGraph::iterator DI = depGraph.outDepBegin(*I);
374        ! DI.fini(); ++DI)
375     {
376       Instruction* sink = &DI->getSink()->getInstr();
377       if (stmtsVisited.find(sink) == stmtsVisited.end())
378         VisitOutEdges(sink, root, depsOfRoot);
379     }
380 }
381
382
383 void FindParallelCalls::visitCallInst(CallInst& CI)
384 {
385   if (completed[&CI])
386     return;
387   stmtsVisited.clear();                      // clear flags to do a fresh DFS
388
389   // Visit all children of CI using a recursive walk through dep graph
390   DependentsSet& depsOfRoot = dependents[&CI];
391   for (PgmDependenceGraph::iterator DI = depGraph.outDepBegin(CI);
392        ! DI.fini(); ++DI)
393     {
394       Instruction* sink = &DI->getSink()->getInstr();
395       if (stmtsVisited.find(sink) == stmtsVisited.end())
396         VisitOutEdges(sink, &CI, depsOfRoot);
397     }
398
399   completed[&CI] = true;
400 }
401
402
403 //---------------------------------------------------------------------------- 
404 // class Parallelize
405 //
406 // (1) Find candidate parallel functions: any function F s.t.
407 //       there is a call C1 to the function F that is followed or preceded
408 //       by at least one other call C2 that is independent of this one
409 //       (i.e., there is no dependence path from C1 to C2 or C2 to C1)
410 // (2) Label such a function F as a cilk function.
411 // (3) Convert every call to F to a spawn
412 // (4) For every function X, insert sync statements so that
413 //        every spawn is postdominated by a sync before any statements
414 //        with a data dependence to/from the call site for the spawn
415 // 
416 //---------------------------------------------------------------------------- 
417
418 namespace {
419   class Parallelize: public Pass
420   {
421   public:
422     /// Driver functions to transform a program
423     ///
424     bool run(Module& M);
425
426     /// getAnalysisUsage - Modifies extensively so preserve nothing.
427     /// Uses the DependenceGraph and the Top-down DS Graph (only to find
428     /// all functions called via an indirect call).
429     ///
430     void getAnalysisUsage(AnalysisUsage &AU) const {
431       AU.addRequired<TDDataStructures>();
432       AU.addRequired<MemoryDepAnalysis>();  // force this not to be released
433       AU.addRequired<PgmDependenceGraph>(); // because it is needed by this
434     }
435   };
436
437   RegisterOpt<Parallelize> X("parallel", "Parallelize program using Cilk");
438 }
439
440
441 static Function* FindMain(Module& M)
442 {
443   for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
444     if (FI->getName() == std::string("main"))
445       return FI;
446   return NULL;
447 }
448
449
450 bool Parallelize::run(Module& M)
451 {
452   hash_set<Function*> parallelFunctions;
453   hash_set<Function*> safeParallelFunctions;
454   hash_set<const GlobalValue*> indirectlyCalled;
455
456   // If there is no main (i.e., for an incomplete program), we can do nothing.
457   // If there is a main, mark main as a parallel function.
458   // 
459   Function* mainFunc = FindMain(M);
460   if (!mainFunc)
461     return false;
462
463   // (1) Find candidate parallel functions and mark them as Cilk functions
464   // 
465   for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
466     if (! FI->isExternal())
467       {
468         Function* F = FI;
469         DSGraph& tdg = getAnalysis<TDDataStructures>().getDSGraph(*F);
470
471         // All the hard analysis work gets done here!
472         // 
473         FindParallelCalls finder(*F,
474                                 getAnalysis<PgmDependenceGraph>().getGraph(*F));
475                         /* getAnalysis<MemoryDepAnalysis>().getGraph(*F)); */
476
477         // Now we know which call instructions are useful to parallelize.
478         // Remember those callee functions.
479         // 
480         for (std::vector<CallInst*>::iterator
481                CII = finder.parallelCalls.begin(),
482                CIE = finder.parallelCalls.end(); CII != CIE; ++CII)
483           {
484             // Check if this is a direct call...
485             if ((*CII)->getCalledFunction() != NULL)
486               { // direct call: if this is to a non-external function,
487                 // mark it as a parallelizable function
488                 if (! (*CII)->getCalledFunction()->isExternal())
489                   parallelFunctions.insert((*CII)->getCalledFunction());
490               }
491             else
492               { // Indirect call: mark all potential callees as bad
493                 std::vector<GlobalValue*> callees =
494                   tdg.getNodeForValue((*CII)->getCalledValue())
495                   .getNode()->getGlobals();
496                 indirectlyCalled.insert(callees.begin(), callees.end());
497               }
498           }
499       }
500
501   // Remove all indirectly called functions from the list of Cilk functions.
502   // 
503   for (hash_set<Function*>::iterator PFI = parallelFunctions.begin(),
504          PFE = parallelFunctions.end(); PFI != PFE; ++PFI)
505     if (indirectlyCalled.count(*PFI) == 0)
506       safeParallelFunctions.insert(*PFI);
507
508 #undef CAN_USE_BIND1ST_ON_REFERENCE_TYPE_ARGS
509 #ifdef CAN_USE_BIND1ST_ON_REFERENCE_TYPE_ARGS
510   // Use this undecipherable STLese because erase invalidates iterators.
511   // Otherwise we have to copy sets as above.
512   hash_set<Function*>::iterator extrasBegin = 
513     std::remove_if(parallelFunctions.begin(), parallelFunctions.end(),
514                    compose1(std::bind2nd(std::greater<int>(), 0),
515                             bind_obj(&indirectlyCalled,
516                                      &hash_set<const GlobalValue*>::count)));
517   parallelFunctions.erase(extrasBegin, parallelFunctions.end());
518 #endif
519
520   // If there are no parallel functions, we can just give up.
521   if (safeParallelFunctions.empty())
522     return false;
523
524   // Add main as a parallel function since Cilk requires this.
525   safeParallelFunctions.insert(mainFunc);
526
527   // (2,3) Transform each Cilk function and all its calls simply by
528   //     adding a unique suffix to the function name.
529   //     This should identify both functions and calls to such functions
530   //     to the code generator.
531   // (4) Also, insert calls to sync at appropriate points.
532   // 
533   Cilkifier cilkifier(M);
534   for (hash_set<Function*>::iterator CFI = safeParallelFunctions.begin(),
535          CFE = safeParallelFunctions.end(); CFI != CFE; ++CFI)
536     {
537       cilkifier.TransformFunc(*CFI, safeParallelFunctions,
538                              getAnalysis<PgmDependenceGraph>().getGraph(**CFI));
539       /* getAnalysis<MemoryDepAnalysis>().getGraph(**CFI)); */
540     }
541
542   return true;
543 }