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