llvm.org GIT mirror llvm / 7e70829
MEGAPATCH checkin. For details, See: docs/2002-06-25-MegaPatchInfo.txt git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@2779 91177308-0d34-0410-b5e6-96231b3b80d8 Chris Lattner 18 years ago
80 changed file(s) with 3009 addition(s) and 1840 deletion(s). Raw diff Collapse all Expand all
77 #ifndef SUPPORT_CASTING_H
88 #define SUPPORT_CASTING_H
99
10 // real_type - Provide a macro to get the real type of a value that might be
11 // a use. This provides a typedef 'Type' that is the argument type for all
12 // non UseTy types, and is the contained pointer type of the use if it is a
13 // UseTy.
14 //
15 template class real_type { typedef X Type; };
16
17 //===----------------------------------------------------------------------===//
18 // Type Checking Templates
19 //===----------------------------------------------------------------------===//
10 #include
11
12 //===----------------------------------------------------------------------===//
13 // isa Support Templates
14 //===----------------------------------------------------------------------===//
15
16 template struct isa_impl_cl;
17
18 // Define a template that can be specialized by smart pointers to reflect the
19 // fact that they are automatically dereferenced, and are not involved with the
20 // template selection process... the default implementation is a noop.
21 //
22 template struct simplify_type {
23 typedef From SimpleType; // The real type this represents...
24
25 // An accessor to get the real value...
26 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
27 };
28
29 template struct simplify_type {
30 typedef const From SimpleType;
31 static SimpleType &getSimplifiedValue(const From &Val) {
32 return simplify_type::getSimplifiedValue((From&)Val);
33 }
34 };
35
2036
2137 // isa - Return true if the parameter to the template is an instance of the
2238 // template type argument. Used like this:
2339 //
24 // if (isa(myVal)) { ... }
25 //
26 template
27 inline bool isa(Y Val) {
28 assert(Val && "isa(NULL) invoked!");
29 return X::classof(Val);
30 }
40 // if (isa(myVal)) { ... }
41 //
42 template
43 inline bool isa_impl(const From &Val) {
44 return To::classof(&Val);
45 }
46
47 template
48 struct isa_impl_wrap {
49 // When From != SimplifiedType, we can simplify the type some more by using
50 // the simplify_type template.
51 static bool doit(const From &Val) {
52 return isa_impl_cl::template
53 isa(simplify_type::getSimplifiedValue(Val));
54 }
55 };
56
57 template
58 struct isa_impl_wrap {
59 // When From == SimpleType, we are as simple as we are going to get.
60 static bool doit(const FromTy &Val) {
61 return isa_impl(Val);
62 }
63 };
64
65 // isa_impl_cl - Use class partial specialization to transform types to a single
66 // cannonical form for isa_impl.
67 //
68 template
69 struct isa_impl_cl {
70 template
71 static bool isa(const FromCl &Val) {
72 return isa_impl_wrap
73 simplify_type::SimpleType>::doit(Val);
74 }
75 };
76
77 // Specialization used to strip const qualifiers off of the FromCl type...
78 template
79 struct isa_impl_cl {
80 template
81 static bool isa(const FromCl &Val) {
82 return isa_impl_cl::template isa(Val);
83 }
84 };
85
86 // Define pointer traits in terms of base traits...
87 template
88 struct isa_impl_cl {
89 template
90 static bool isa(FromCl *Val) {
91 return isa_impl_cl::template isa(*Val);
92 }
93 };
94
95 // Define reference traits in terms of base traits...
96 template
97 struct isa_impl_cl {
98 template
99 static bool isa(FromCl &Val) {
100 return isa_impl_cl::template isa(&Val);
101 }
102 };
103
104 template
105 inline bool isa(const Y &Val) {
106 return isa_impl_cl::template isa(Val);
107 }
108
109 //===----------------------------------------------------------------------===//
110 // cast Support Templates
111 //===----------------------------------------------------------------------===//
112
113 template struct cast_retty;
114
115
116 // Calculate what type the 'cast' function should return, based on a requested
117 // type of To and a source type of From.
118 template struct cast_retty_impl {
119 typedef To& ret_type; // Normal case, return Ty&
120 };
121 template struct cast_retty_impl {
122 typedef const To &ret_type; // Normal case, return Ty&
123 };
124
125 template struct cast_retty_impl {
126 typedef To* ret_type; // Pointer arg case, return Ty*
127 };
128
129 template struct cast_retty_impl {
130 typedef const To* ret_type; // Constant pointer arg case, return const Ty*
131 };
132
133 template struct cast_retty_impl {
134 typedef const To* ret_type; // Constant pointer arg case, return const Ty*
135 };
136
137
138 template
139 struct cast_retty_wrap {
140 // When the simplified type and the from type are not the same, use the type
141 // simplifier to reduce the type, then reuse cast_retty_impl to get the
142 // resultant type.
143 typedef typename cast_retty::ret_type ret_type;
144 };
145
146 template
147 struct cast_retty_wrap {
148 // When the simplified type is equal to the from type, use it directly.
149 typedef typename cast_retty_impl::ret_type ret_type;
150 };
151
152 template
153 struct cast_retty {
154 typedef typename cast_retty_wrap
155 simplify_type::SimpleType>::ret_type ret_type;
156 };
157
158 // Ensure the non-simple values are converted using the simplify_type template
159 // that may be specialized by smart pointers...
160 //
161 template struct cast_convert_val {
162 // This is not a simple type, use the template to simplify it...
163 static cast_retty::ret_type doit(const From &Val) {
164 return cast_convert_val
165 simplify_type::SimpleType>::doit(
166 simplify_type::getSimplifiedValue(Val));
167 }
168 };
169
170 template struct cast_convert_val {
171 // This _is_ a simple type, just cast it.
172 static cast_retty::ret_type doit(const FromTy &Val) {
173 return (cast_retty::ret_type)Val;
174 }
175 };
176
31177
32178
33179 // cast - Return the argument parameter cast to the specified type. This
35181 // on failure. But it will correctly return NULL when the input is NULL.
36182 // Used Like this:
37183 //
38 // cast< Instruction>(myVal)->getParent()
39 // cast(myVal)->getParent()
40 //
41 template
42 inline X *cast(Y Val) {
184 // cast(myVal)->getParent()
185 //
186 template
187 inline cast_retty::ret_type cast(const Y &Val) {
43188 assert(isa(Val) && "cast() argument of uncompatible type!");
44 return (X*)(real_type::Type)Val;
189 return cast_convert_val::SimpleType>::doit(Val);
45190 }
46191
47192 // cast_or_null - Functionally identical to cast, except that a null value is
48193 // accepted.
49194 //
50195 template
51 inline X *cast_or_null(Y Val) {
52 assert((Val == 0 || isa(Val)) &&
53 "cast_or_null() argument of uncompatible type!");
54 return (X*)(real_type::Type)Val;
196 inline cast_retty::ret_type cast_or_null(Y *Val) {
197 if (Val == 0) return 0;
198 assert(isa(Val) && "cast_or_null() argument of uncompatible type!");
199 return cast(Val);
55200 }
56201
57202
64209 //
65210
66211 template
67 inline X *dyn_cast(Y Val) {
68 return isa(Val) ? cast(Val) : 0;
212 inline cast_retty::ret_type dyn_cast(Y *Val) {
213 return isa(Val) ? cast(Val) : 0;
69214 }
70215
71216 // dyn_cast_or_null - Functionally identical to dyn_cast, except that a null
72217 // value is accepted.
73218 //
74219 template
75 inline X *dyn_cast_or_null(Y Val) {
76 return (Val && isa(Val)) ? cast(Val) : 0;
220 inline cast_retty::ret_type dyn_cast_or_null(Y *Val) {
221 return (Val && isa(Val)) ? cast(Val) : 0;
222 }
223
224
225 #ifdef DEBUG_CAST_OPERATORS
226 #include
227
228 struct bar {
229 bar() {}
230 private:
231 bar(const bar &);
232 };
233 struct foo {
234 void ext() const;
235 /* static bool classof(const bar *X) {
236 cerr << "Classof: " << X << "\n";
237 return true;
238 }*/
239 };
240
241 template <> inline bool isa_impl(const bar &Val) {
242 cerr << "Classof: " << &Val << "\n";
243 return true;
244 }
245
246
247 bar *fub();
248 void test(bar &B1, const bar *B2) {
249 // test various configurations of const
250 const bar &B3 = B1;
251 const bar *const B4 = B2;
252
253 // test isa
254 if (!isa(B1)) return;
255 if (!isa(B2)) return;
256 if (!isa(B3)) return;
257 if (!isa(B4)) return;
258
259 // test cast
260 foo &F1 = cast(B1);
261 const foo *F3 = cast(B2);
262 const foo *F4 = cast(B2);
263 const foo &F8 = cast(B3);
264 const foo *F9 = cast(B4);
265 foo *F10 = cast(fub());
266
267 // test cast_or_null
268 const foo *F11 = cast_or_null(B2);
269 const foo *F12 = cast_or_null(B2);
270 const foo *F13 = cast_or_null(B4);
271 const foo *F14 = cast_or_null(fub()); // Shouldn't print.
272
273 // These lines are errors...
274 //foo *F20 = cast(B2); // Yields const foo*
275 //foo &F21 = cast(B3); // Yields const foo&
276 //foo *F22 = cast(B4); // Yields const foo*
277 //foo &F23 = cast_or_null(B1);
278 //const foo &F24 = cast_or_null(B3);
279 }
280
281 bar *fub() { return 0; }
282 void main() {
283 bar B;
284 test(B, &B);
77285 }
78286
79287 #endif
288
289 #endif
0 //===-- - Intrusive Linked List Template ---------*- C++ -*--=//
1 //
2 // This file defines classes to implement an intrusive doubly linked list class
3 // (ie each node of the list must contain a next and previous field for the
4 // list.
5 //
6 // The ilist_traits trait class is used to gain access to the next and previous
7 // fields of the node type that the list is instantiated with. If it is not
8 // specialized, the list defaults to using the getPrev(), getNext() method calls
9 // to get the next and previous pointers.
10 //
11 // The ilist class itself, should be a plug in replacement for list, assuming
12 // that the nodes contain next/prev pointers. This list replacement does not
13 // provides a constant time size() method, so be careful to use empty() when you
14 // really want to know if I'm empty.
15 //
16 // The ilist class is implemented by allocating a 'tail' node when the list is
17 // created (using ilist_traits<>::createEndMarker()). This tail node is
18 // absolutely required because the user must be able to compute end()-1. Because
19 // of this, users of the direct next/prev links will see an extra link on the
20 // end of the list, which should be ignored.
21 //
22 // Requirements for a user of this list:
23 //
24 // 1. The user must provide {g|s}et{Next|Prev} methods, or specialize
25 // ilist_traits to provide an alternate way of getting and setting next and
26 // prev links.
27 //
28 //===----------------------------------------------------------------------===//
29
30 #ifndef INCLUDED_SUPPORT_ILIST
31 #define INCLUDED_SUPPORT_ILIST
32
33 #include
34 #include
35
36 template class iplist;
37 template class ilist_iterator;
38
39 // Template traits for intrusive list. By specializing this template class, you
40 // can change what next/prev fields are used to store the links...
41 template
42 struct ilist_traits {
43 static NodeTy *getPrev(NodeTy *N) { return N->getPrev(); }
44 static NodeTy *getNext(NodeTy *N) { return N->getNext(); }
45 static const NodeTy *getPrev(const NodeTy *N) { return N->getPrev(); }
46 static const NodeTy *getNext(const NodeTy *N) { return N->getNext(); }
47
48 static void setPrev(NodeTy *N, NodeTy *Prev) { N->setPrev(Prev); }
49 static void setNext(NodeTy *N, NodeTy *Next) { N->setNext(Next); }
50
51 static NodeTy *createNode() { return new NodeTy(); }
52 static NodeTy *createNode(const NodeTy &V) { return new NodeTy(V); }
53
54
55 void addNodeToList(NodeTy *NTy) {}
56 void removeNodeFromList(NodeTy *NTy) {}
57 void transferNodesFromList(iplist &L2,
58 ilist_iterator first,
59 ilist_iterator last) {}
60 };
61
62 // Const traits are the same as nonconst traits...
63 template
64 struct ilist_traits : public ilist_traits {};
65
66
67 //===----------------------------------------------------------------------===//
68 // ilist_iterator - Iterator for intrusive list.
69 //
70 template
71 class ilist_iterator : public std::bidirectional_iterator {
72 typedef ilist_traits Traits;
73 pointer NodePtr;
74 public:
75 typedef size_t size_type;
76
77 ilist_iterator(pointer NP) : NodePtr(NP) {}
78 ilist_iterator() : NodePtr(0) {}
79
80 // This is templated so that we can allow constructing a const iterator from
81 // a nonconst iterator...
82 template
83 ilist_iterator(const ilist_iterator &RHS)
84 : NodePtr(RHS.getNodePtrUnchecked()) {}
85
86 // This is templated so that we can allow assigning to a const iterator from
87 // a nonconst iterator...
88 template
89 const ilist_iterator &operator=(const ilist_iterator &RHS) {
90 NodePtr = RHS.getNodePtrUnchecked();
91 return *this;
92 }
93
94 // Accessors...
95 operator pointer() const {
96 assert(Traits::getNext(NodePtr) != 0 && "Dereferencing end()!");
97 return NodePtr;
98 }
99
100 reference operator*() const {
101 assert(Traits::getNext(NodePtr) != 0 && "Dereferencing end()!");
102 return *NodePtr;
103 }
104 pointer operator->() { return &operator*(); }
105 const pointer operator->() const { return &operator*(); }
106
107 // Comparison operators
108 bool operator==(const ilist_iterator &RHS) const {
109 return NodePtr == RHS.NodePtr;
110 }
111 bool operator!=(const ilist_iterator &RHS) const {
112 return NodePtr != RHS.NodePtr;
113 }
114
115 // Increment and decrement operators...
116 ilist_iterator &operator--() { // predecrement - Back up
117 NodePtr = Traits::getPrev(NodePtr);
118 assert(NodePtr && "--'d off the beginning of an ilist!");
119 return *this;
120 }
121 ilist_iterator &operator++() { // preincrement - Advance
122 NodePtr = Traits::getNext(NodePtr);
123 assert(NodePtr && "++'d off the end of an ilist!");
124 return *this;
125 }
126 ilist_iterator operator--(int) { // postdecrement operators...
127 ilist_iterator tmp = *this;
128 --*this;
129 return tmp;
130 }
131 ilist_iterator operator++(int) { // postincrement operators...
132 ilist_iterator tmp = *this;
133 ++*this;
134 return tmp;
135 }
136
137
138 // Dummy operators to make errors apparent...
139 template void operator+(X Val) {}
140 template void operator-(X Val) {}
141
142 // Internal interface, do not use...
143 pointer getNodePtrUnchecked() const { return NodePtr; }
144 };
145
146
147 //===----------------------------------------------------------------------===//
148 //
149 // iplist - The subset of list functionality that can safely be used on nodes of
150 // polymorphic types, ie a heterogeneus list with a common base class that holds
151 // the next/prev pointers...
152 //
153 template >
154 class iplist : public Traits {
155 NodeTy *Head, *Tail;
156
157 static bool op_less(NodeTy &L, NodeTy &R) { return L < R; }
158 static bool op_equal(NodeTy &L, NodeTy &R) { return L == R; }
159 public:
160 typedef NodeTy *pointer;
161 typedef const NodeTy *const_pointer;
162 typedef NodeTy &reference;
163 typedef const NodeTy &const_reference;
164 typedef NodeTy value_type;
165 typedef ilist_iterator iterator;
166 typedef ilist_iterator const_iterator;
167 typedef size_t size_type;
168 typedef ptrdiff_t difference_type;
169 typedef reverse_iterator const_reverse_iterator;
170 typedef reverse_iterator reverse_iterator;
171
172 iplist() : Head(createNode()), Tail(Head) {
173 setNext(Head, 0);
174 setPrev(Head, 0);
175 }
176 ~iplist() { clear(); delete Tail; }
177
178 // Iterator creation methods...
179 iterator begin() { return iterator(Head); }
180 const_iterator begin() const { return const_iterator(Head); }
181 iterator end() { return iterator(Tail); }
182 const_iterator end() const { return const_iterator(Tail); }
183
184 // reverse iterator creation methods...
185 reverse_iterator rbegin() { return reverse_iterator(end()); }
186 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
187 reverse_iterator rend() { return reverse_iterator(begin()); }
188 const_reverse_iterator rend() const {return const_reverse_iterator(begin());}
189
190 // Miscellaneous inspection routines...
191 size_type max_size() const { return size_type(-1); }
192 bool empty() const { return Head == Tail; }
193
194 // Front and back accessor functions...
195 reference front() {
196 assert(!empty() && "Called front() on empty list!");
197 return *Head;
198 }
199 const_reference front() const {
200 assert(!empty() && "Called front() on empty list!");
201 return *Head;
202 }
203 reference back() {
204 assert(!empty() && "Called back() on empty list!");
205 return *getPrev(Tail);
206 }
207 const_reference back() const {
208 assert(!empty() && "Called back() on empty list!");
209 return *getPrev(Tail);
210 }
211
212 void swap(iplist &RHS) {
213 abort(); // Swap does not use list traits callback correctly yet!
214 std::swap(Head, RHS.Head);
215 std::swap(Tail, RHS.Tail);
216 }
217
218 iterator insert(iterator where, NodeTy *New) {
219 NodeTy *CurNode = where.getNodePtrUnchecked(), *PrevNode = getPrev(CurNode);
220 setNext(New, CurNode);
221 setPrev(New, PrevNode);
222
223 if (PrevNode)
224 setNext(PrevNode, New);
225 else
226 Head = New;
227 setPrev(CurNode, New);
228
229 addNodeToList(New); // Notify traits that we added a node...
230 return New;
231 }
232
233 NodeTy *remove(iterator &IT) {
234 assert(IT != end() && "Cannot remove end of list!");
235 NodeTy *Node = &*IT;
236 NodeTy *NextNode = getNext(Node);
237 NodeTy *PrevNode = getPrev(Node);
238
239 if (PrevNode)
240 setNext(PrevNode, NextNode);
241 else
242 Head = NextNode;
243 setPrev(NextNode, PrevNode);
244 IT = NextNode;
245 removeNodeFromList(Node); // Notify traits that we added a node...
246 return Node;
247 }
248
249 NodeTy *remove(const iterator &IT) {
250 iterator MutIt = IT;
251 return remove(MutIt);
252 }
253
254 // erase - remove a node from the controlled sequence... and delete it.
255 iterator erase(iterator where) {
256 delete remove(where);
257 return where;
258 }
259
260
261 private:
262 // transfer - The heart of the splice function. Move linked list nodes from
263 // [first, last) into position.
264 //
265 void transfer(iterator position, iplist &L2, iterator first, iterator last) {
266 assert(first != last && "Should be checked by callers");
267 if (position != last) {
268 // Remove [first, last) from its old position.
269 NodeTy *First = &*first, *Prev = getPrev(First);
270 NodeTy *Next = last.getNodePtrUnchecked(), *Last = getPrev(Next);
271 if (Prev)
272 setNext(Prev, Next);
273 else
274 L2.Head = Next;
275 setPrev(Next, Prev);
276
277 // Splice [first, last) into its new position.
278 NodeTy *PosNext = position.getNodePtrUnchecked();
279 NodeTy *PosPrev = getPrev(PosNext);
280
281 // Fix head of list...
282 if (PosPrev)
283 setNext(PosPrev, First);
284 else
285 Head = First;
286 setPrev(First, PosPrev);
287
288 // Fix end of list...
289 setNext(Last, PosNext);
290 setPrev(PosNext, Last);
291
292 transferNodesFromList(L2, First, PosNext);
293 }
294 }
295
296 public:
297
298 //===----------------------------------------------------------------------===
299 // Functionality derived from other functions defined above...
300 //
301
302 size_type size() const {
303 size_type Result = 0;
304 std::distance(begin(), end(), Result);
305 return Result;
306 }
307
308 iterator erase(iterator first, iterator last) {
309 while (first != last)
310 first = erase(first);
311 return last;
312 }
313
314 void clear() { erase(begin(), end()); }
315
316 // Front and back inserters...
317 void push_front(NodeTy *val) { insert(begin(), val); }
318 void push_back(NodeTy *val) { insert(end(), val); }
319 void pop_front() {
320 assert(!empty() && "pop_front() on empty list!");
321 erase(begin());
322 }
323 void pop_back() {
324 assert(!empty() && "pop_back() on empty list!");
325 iterator t = end(); erase(--t);
326 }
327
328 // Special forms of insert...
329 template void insert(iterator where, InIt first, InIt last) {
330 for (; first != last; ++first) insert(where, *first);
331 }
332
333 // Splice members - defined in terms of transfer...
334 void splice(iterator where, iplist &L2) {
335 if (!L2.empty())
336 transfer(where, L2, L2.begin(), L2.end());
337 }
338 void splice(iterator where, iplist &L2, iterator first) {
339 iterator last = first; ++last;
340 if (where == first || where == last) return; // No change
341 transfer(where, L2, first, last);
342 }
343 void splice(iterator where, iplist &L2, iterator first, iterator last) {
344 if (first != last) transfer(where, L2, first, last);
345 }
346
347
348
349 //===----------------------------------------------------------------------===
350 // High-Level Functionality that shouldn't really be here, but is part of list
351 //
352
353 // These two functions are actually called remove/remove_if in list<>, but
354 // they actually do the job of erase, rename them accordingly.
355 //
356 void erase(const NodeTy &val) {
357 for (iterator I = begin(), E = end(); I != E; ) {
358 iterator next = I; ++next;
359 if (*I == val) erase(I);
360 I = next;
361 }
362 }
363 template void erase_if(Pr1 pred) {
364 for (iterator I = begin(), E = end(); I != E; ) {
365 iterator next = I; ++next;
366 if (pred(*I)) erase(I);
367 I = next;
368 }
369 }
370
371 template void unique(Pr2 pred) {
372 if (empty()) return;
373 for (iterator I = begin(), E = end(), Next = begin(); ++Next != E;) {
374 if (pred(*I))
375 erase(Next);
376 else
377 I = Next;
378 Next = I;
379 }
380 }
381 void unique() { unique(op_equal); }
382
383 template void merge(iplist &right, Pr3 pred) {
384 iterator first1 = begin(), last1 = end();
385 iterator first2 = right.begin(), last2 = right.end();
386 while (first1 != last1 && first2 != last2)
387 if (pred(*first2, *first1)) {
388 iterator next = first2;
389 transfer(first1, right, first2, ++next);
390 first2 = next;
391 } else {
392 ++first1;
393 }
394 if (first2 != last2) transfer(last1, right, first2, last2);
395 }
396 void merge(iplist &right) { return merge(right, op_less); }
397
398 template void sort(Pr3 pred);
399 void sort() { sort(op_less); }
400 void reverse();
401 };
402
403
404 template
405 struct ilist : public iplist {
406 ilist() {}
407 ilist(const ilist &right) {
408 insert(begin(), right.begin(), right.end());
409 }
410 explicit ilist(size_type count) {
411 insert(begin(), count, NodeTy());
412 }
413 ilist(size_type count, const NodeTy &val) {
414 insert(begin(), count, val);
415 }
416 template ilist(InIt first, InIt last) {
417 insert(begin(), first, last);
418 }
419
420
421 // Forwarding functions: A workaround for GCC 2.95 which does not correctly
422 // support 'using' declarations to bring a hidden member into scope.
423 //
424 iterator insert(iterator a, NodeTy *b){ return iplist::insert(a, b); }
425 void push_front(NodeTy *a) { iplist::push_front(a); }
426 void push_back(NodeTy *a) { iplist::push_back(a); }
427
428
429 // Main implementation here - Insert for a node passed by value...
430 iterator insert(iterator where, const NodeTy &val) {
431 return insert(where, createNode(val));
432 }
433
434
435 // Front and back inserters...
436 void push_front(const NodeTy &val) { insert(begin(), val); }
437 void push_back(const NodeTy &val) { insert(end(), val); }
438
439 // Special forms of insert...
440 template void insert(iterator where, InIt first, InIt last) {
441 for (; first != last; ++first) insert(where, *first);
442 }
443 void insert(iterator where, size_type count, const NodeTy &val) {
444 for (; count != 0; --count) insert(where, val);
445 }
446
447 // Assign special forms...
448 void assign(size_type count, const NodeTy &val) {
449 iterator I = begin();
450 for (; I != end() && count != 0; ++I, --count)
451 *I = val;
452 if (count != 0)
453 insert(end(), n, val);
454 else
455 erase(I, end());
456 }
457 template void assign(InIt first, InIt last) {
458 iterator first1 = begin(), last1 = end();
459 for ( ; first1 != last1 && first2 != last2; ++first1, ++first2)
460 *first1 = *first2;
461 if (first2 == last2)
462 erase(first1, last1);
463 else
464 insert(last1, first2, last2);
465 }
466
467
468 // Resize members...
469 void resize(size_type newsize, NodeTy val) {
470 iterator i = begin();
471 size_type len = 0;
472 for ( ; i != end() && len < newsize; ++i, ++len) /* empty*/ ;
473
474 if (len == newsize)
475 erase(i, end());
476 else // i == end()
477 insert(end(), newsize - len, val);
478 }
479 void resize(size_type newsize) { resize(newsize, NodeTy()); }
480
481 };
482
483 namespace std {
484 // Ensure that swap uses the fast list swap...
485 template
486 void swap(iplist &Left, iplist &Right) {
487 Left.swap(Right);
488 }
489 } // End 'std' extensions...
490
491 #endif
0 //===-- - Intrusive Linked List Template ---------*- C++ -*--=//
1 //
2 // This file defines classes to implement an intrusive doubly linked list class
3 // (ie each node of the list must contain a next and previous field for the
4 // list.
5 //
6 // The ilist_traits trait class is used to gain access to the next and previous
7 // fields of the node type that the list is instantiated with. If it is not
8 // specialized, the list defaults to using the getPrev(), getNext() method calls
9 // to get the next and previous pointers.
10 //
11 // The ilist class itself, should be a plug in replacement for list, assuming
12 // that the nodes contain next/prev pointers. This list replacement does not
13 // provides a constant time size() method, so be careful to use empty() when you
14 // really want to know if I'm empty.
15 //
16 // The ilist class is implemented by allocating a 'tail' node when the list is
17 // created (using ilist_traits<>::createEndMarker()). This tail node is
18 // absolutely required because the user must be able to compute end()-1. Because
19 // of this, users of the direct next/prev links will see an extra link on the
20 // end of the list, which should be ignored.
21 //
22 // Requirements for a user of this list:
23 //
24 // 1. The user must provide {g|s}et{Next|Prev} methods, or specialize
25 // ilist_traits to provide an alternate way of getting and setting next and
26 // prev links.
27 //
28 //===----------------------------------------------------------------------===//
29
30 #ifndef INCLUDED_SUPPORT_ILIST
31 #define INCLUDED_SUPPORT_ILIST
32
33 #include
34 #include
35
36 template class iplist;
37 template class ilist_iterator;
38
39 // Template traits for intrusive list. By specializing this template class, you
40 // can change what next/prev fields are used to store the links...
41 template
42 struct ilist_traits {
43 static NodeTy *getPrev(NodeTy *N) { return N->getPrev(); }
44 static NodeTy *getNext(NodeTy *N) { return N->getNext(); }
45 static const NodeTy *getPrev(const NodeTy *N) { return N->getPrev(); }
46 static const NodeTy *getNext(const NodeTy *N) { return N->getNext(); }
47
48 static void setPrev(NodeTy *N, NodeTy *Prev) { N->setPrev(Prev); }
49 static void setNext(NodeTy *N, NodeTy *Next) { N->setNext(Next); }
50
51 static NodeTy *createNode() { return new NodeTy(); }
52 static NodeTy *createNode(const NodeTy &V) { return new NodeTy(V); }
53
54
55 void addNodeToList(NodeTy *NTy) {}
56 void removeNodeFromList(NodeTy *NTy) {}
57 void transferNodesFromList(iplist &L2,
58 ilist_iterator first,
59 ilist_iterator last) {}
60 };
61
62 // Const traits are the same as nonconst traits...
63 template
64 struct ilist_traits : public ilist_traits {};
65
66
67 //===----------------------------------------------------------------------===//
68 // ilist_iterator - Iterator for intrusive list.
69 //
70 template
71 class ilist_iterator : public std::bidirectional_iterator {
72 typedef ilist_traits Traits;
73 pointer NodePtr;
74 public:
75 typedef size_t size_type;
76
77 ilist_iterator(pointer NP) : NodePtr(NP) {}
78 ilist_iterator() : NodePtr(0) {}
79
80 // This is templated so that we can allow constructing a const iterator from
81 // a nonconst iterator...
82 template
83 ilist_iterator(const ilist_iterator &RHS)
84 : NodePtr(RHS.getNodePtrUnchecked()) {}
85
86 // This is templated so that we can allow assigning to a const iterator from
87 // a nonconst iterator...
88 template
89 const ilist_iterator &operator=(const ilist_iterator &RHS) {
90 NodePtr = RHS.getNodePtrUnchecked();
91 return *this;
92 }
93
94 // Accessors...
95 operator pointer() const {
96 assert(Traits::getNext(NodePtr) != 0 && "Dereferencing end()!");
97 return NodePtr;
98 }
99
100 reference operator*() const {
101 assert(Traits::getNext(NodePtr) != 0 && "Dereferencing end()!");
102 return *NodePtr;
103 }
104 pointer operator->() { return &operator*(); }
105 const pointer operator->() const { return &operator*(); }
106
107 // Comparison operators
108 bool operator==(const ilist_iterator &RHS) const {
109 return NodePtr == RHS.NodePtr;
110 }
111 bool operator!=(const ilist_iterator &RHS) const {
112 return NodePtr != RHS.NodePtr;
113 }
114
115 // Increment and decrement operators...
116 ilist_iterator &operator--() { // predecrement - Back up
117 NodePtr = Traits::getPrev(NodePtr);
118 assert(NodePtr && "--'d off the beginning of an ilist!");
119 return *this;
120 }
121 ilist_iterator &operator++() { // preincrement - Advance
122 NodePtr = Traits::getNext(NodePtr);
123 assert(NodePtr && "++'d off the end of an ilist!");
124 return *this;
125 }
126 ilist_iterator operator--(int) { // postdecrement operators...
127 ilist_iterator tmp = *this;
128 --*this;
129 return tmp;
130 }
131 ilist_iterator operator++(int) { // postincrement operators...
132 ilist_iterator tmp = *this;
133 ++*this;
134 return tmp;
135 }
136
137
138 // Dummy operators to make errors apparent...
139 template void operator+(X Val) {}
140 template void operator-(X Val) {}
141
142 // Internal interface, do not use...
143 pointer getNodePtrUnchecked() const { return NodePtr; }
144 };
145
146
147 //===----------------------------------------------------------------------===//
148 //
149 // iplist - The subset of list functionality that can safely be used on nodes of
150 // polymorphic types, ie a heterogeneus list with a common base class that holds
151 // the next/prev pointers...
152 //
153 template >
154 class iplist : public Traits {
155 NodeTy *Head, *Tail;
156
157 static bool op_less(NodeTy &L, NodeTy &R) { return L < R; }
158 static bool op_equal(NodeTy &L, NodeTy &R) { return L == R; }
159 public:
160 typedef NodeTy *pointer;
161 typedef const NodeTy *const_pointer;
162 typedef NodeTy &reference;
163 typedef const NodeTy &const_reference;
164 typedef NodeTy value_type;
165 typedef ilist_iterator iterator;
166 typedef ilist_iterator const_iterator;
167 typedef size_t size_type;
168 typedef ptrdiff_t difference_type;
169 typedef reverse_iterator const_reverse_iterator;
170 typedef reverse_iterator reverse_iterator;
171
172 iplist() : Head(createNode()), Tail(Head) {
173 setNext(Head, 0);
174 setPrev(Head, 0);
175 }
176 ~iplist() { clear(); delete Tail; }
177
178 // Iterator creation methods...
179 iterator begin() { return iterator(Head); }
180 const_iterator begin() const { return const_iterator(Head); }
181 iterator end() { return iterator(Tail); }
182 const_iterator end() const { return const_iterator(Tail); }
183
184 // reverse iterator creation methods...
185 reverse_iterator rbegin() { return reverse_iterator(end()); }
186 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
187 reverse_iterator rend() { return reverse_iterator(begin()); }
188 const_reverse_iterator rend() const {return const_reverse_iterator(begin());}
189
190 // Miscellaneous inspection routines...
191 size_type max_size() const { return size_type(-1); }
192 bool empty() const { return Head == Tail; }
193
194 // Front and back accessor functions...
195 reference front() {
196 assert(!empty() && "Called front() on empty list!");
197 return *Head;
198 }
199 const_reference front() const {
200 assert(!empty() && "Called front() on empty list!");
201 return *Head;
202 }
203 reference back() {
204 assert(!empty() && "Called back() on empty list!");
205 return *getPrev(Tail);
206 }
207 const_reference back() const {
208 assert(!empty() && "Called back() on empty list!");
209 return *getPrev(Tail);
210 }
211
212 void swap(iplist &RHS) {
213 abort(); // Swap does not use list traits callback correctly yet!
214 std::swap(Head, RHS.Head);
215 std::swap(Tail, RHS.Tail);
216 }
217
218 iterator insert(iterator where, NodeTy *New) {
219 NodeTy *CurNode = where.getNodePtrUnchecked(), *PrevNode = getPrev(CurNode);
220 setNext(New, CurNode);
221 setPrev(New, PrevNode);
222
223 if (PrevNode)
224 setNext(PrevNode, New);
225 else
226 Head = New;
227 setPrev(CurNode, New);
228
229 addNodeToList(New); // Notify traits that we added a node...
230 return New;
231 }
232
233 NodeTy *remove(iterator &IT) {
234 assert(IT != end() && "Cannot remove end of list!");
235 NodeTy *Node = &*IT;
236 NodeTy *NextNode = getNext(Node);
237 NodeTy *PrevNode = getPrev(Node);
238
239 if (PrevNode)
240 setNext(PrevNode, NextNode);
241 else
242 Head = NextNode;
243 setPrev(NextNode, PrevNode);
244 IT = NextNode;
245 removeNodeFromList(Node); // Notify traits that we added a node...
246 return Node;
247 }
248
249 NodeTy *remove(const iterator &IT) {
250 iterator MutIt = IT;
251 return remove(MutIt);
252 }
253
254 // erase - remove a node from the controlled sequence... and delete it.
255 iterator erase(iterator where) {
256 delete remove(where);
257 return where;
258 }
259
260
261 private:
262 // transfer - The heart of the splice function. Move linked list nodes from
263 // [first, last) into position.
264 //
265 void transfer(iterator position, iplist &L2, iterator first, iterator last) {
266 assert(first != last && "Should be checked by callers");
267 if (position != last) {
268 // Remove [first, last) from its old position.
269 NodeTy *First = &*first, *Prev = getPrev(First);
270 NodeTy *Next = last.getNodePtrUnchecked(), *Last = getPrev(Next);
271 if (Prev)
272 setNext(Prev, Next);
273 else
274 L2.Head = Next;
275 setPrev(Next, Prev);
276
277 // Splice [first, last) into its new position.
278 NodeTy *PosNext = position.getNodePtrUnchecked();
279 NodeTy *PosPrev = getPrev(PosNext);
280
281 // Fix head of list...
282 if (PosPrev)
283 setNext(PosPrev, First);
284 else
285 Head = First;
286 setPrev(First, PosPrev);
287
288 // Fix end of list...
289 setNext(Last, PosNext);
290 setPrev(PosNext, Last);
291
292 transferNodesFromList(L2, First, PosNext);
293 }
294 }
295
296 public:
297
298 //===----------------------------------------------------------------------===
299 // Functionality derived from other functions defined above...
300 //
301
302 size_type size() const {
303 size_type Result = 0;
304 std::distance(begin(), end(), Result);
305 return Result;
306 }
307
308 iterator erase(iterator first, iterator last) {
309 while (first != last)
310 first = erase(first);
311 return last;
312 }
313
314 void clear() { erase(begin(), end()); }
315
316 // Front and back inserters...
317 void push_front(NodeTy *val) { insert(begin(), val); }
318 void push_back(NodeTy *val) { insert(end(), val); }
319 void pop_front() {
320 assert(!empty() && "pop_front() on empty list!");
321 erase(begin());
322 }
323 void pop_back() {
324 assert(!empty() && "pop_back() on empty list!");
325 iterator t = end(); erase(--t);
326 }
327
328 // Special forms of insert...
329 template void insert(iterator where, InIt first, InIt last) {
330 for (; first != last; ++first) insert(where, *first);
331 }
332
333 // Splice members - defined in terms of transfer...
334 void splice(iterator where, iplist &L2) {
335 if (!L2.empty())
336 transfer(where, L2, L2.begin(), L2.end());
337 }
338 void splice(iterator where, iplist &L2, iterator first) {
339 iterator last = first; ++last;
340 if (where == first || where == last) return; // No change
341 transfer(where, L2, first, last);
342 }
343 void splice(iterator where, iplist &L2, iterator first, iterator last) {
344 if (first != last) transfer(where, L2, first, last);
345 }
346
347
348
349 //===----------------------------------------------------------------------===
350 // High-Level Functionality that shouldn't really be here, but is part of list
351 //
352
353 // These two functions are actually called remove/remove_if in list<>, but
354 // they actually do the job of erase, rename them accordingly.
355 //
356 void erase(const NodeTy &val) {
357 for (iterator I = begin(), E = end(); I != E; ) {
358 iterator next = I; ++next;
359 if (*I == val) erase(I);
360 I = next;
361 }
362 }
363 template void erase_if(Pr1 pred) {
364 for (iterator I = begin(), E = end(); I != E; ) {
365 iterator next = I; ++next;
366 if (pred(*I)) erase(I);
367 I = next;
368 }
369 }
370
371 template void unique(Pr2 pred) {
372 if (empty()) return;
373 for (iterator I = begin(), E = end(), Next = begin(); ++Next != E;) {
374 if (pred(*I))
375 erase(Next);
376 else
377 I = Next;
378 Next = I;
379 }
380 }
381 void unique() { unique(op_equal); }
382
383 template void merge(iplist &right, Pr3 pred) {
384 iterator first1 = begin(), last1 = end();
385 iterator first2 = right.begin(), last2 = right.end();
386 while (first1 != last1 && first2 != last2)
387 if (pred(*first2, *first1)) {
388 iterator next = first2;
389 transfer(first1, right, first2, ++next);
390 first2 = next;
391 } else {
392 ++first1;
393 }
394 if (first2 != last2) transfer(last1, right, first2, last2);
395 }
396 void merge(iplist &right) { return merge(right, op_less); }
397
398 template void sort(Pr3 pred);
399 void sort() { sort(op_less); }
400 void reverse();
401 };
402
403
404 template
405 struct ilist : public iplist {
406 ilist() {}
407 ilist(const ilist &right) {
408 insert(begin(), right.begin(), right.end());
409 }
410 explicit ilist(size_type count) {
411 insert(begin(), count, NodeTy());
412 }
413 ilist(size_type count, const NodeTy &val) {
414 insert(begin(), count, val);
415 }
416 template ilist(InIt first, InIt last) {
417 insert(begin(), first, last);
418 }
419
420
421 // Forwarding functions: A workaround for GCC 2.95 which does not correctly
422 // support 'using' declarations to bring a hidden member into scope.
423 //
424 iterator insert(iterator a, NodeTy *b){ return iplist::insert(a, b); }
425 void push_front(NodeTy *a) { iplist::push_front(a); }
426 void push_back(NodeTy *a) { iplist::push_back(a); }
427
428
429 // Main implementation here - Insert for a node passed by value...
430 iterator insert(iterator where, const NodeTy &val) {
431 return insert(where, createNode(val));
432 }
433
434
435 // Front and back inserters...
436 void push_front(const NodeTy &val) { insert(begin(), val); }
437 void push_back(const NodeTy &val) { insert(end(), val); }
438
439 // Special forms of insert...
440 template void insert(iterator where, InIt first, InIt last) {
441 for (; first != last; ++first) insert(where, *first);
442 }
443 void insert(iterator where, size_type count, const NodeTy &val) {
444 for (; count != 0; --count) insert(where, val);
445 }
446
447 // Assign special forms...
448 void assign(size_type count, const NodeTy &val) {
449 iterator I = begin();
450 for (; I != end() && count != 0; ++I, --count)
451 *I = val;
452 if (count != 0)
453 insert(end(), n, val);
454 else
455 erase(I, end());
456 }
457 template void assign(InIt first, InIt last) {
458 iterator first1 = begin(), last1 = end();
459 for ( ; first1 != last1 && first2 != last2; ++first1, ++first2)
460 *first1 = *first2;
461 if (first2 == last2)
462 erase(first1, last1);
463 else
464 insert(last1, first2, last2);
465 }
466
467
468 // Resize members...
469 void resize(size_type newsize, NodeTy val) {
470 iterator i = begin();
471 size_type len = 0;
472 for ( ; i != end() && len < newsize; ++i, ++len) /* empty*/ ;
473
474 if (len == newsize)
475 erase(i, end());
476 else // i == end()
477 insert(end(), newsize - len, val);
478 }
479 void resize(size_type newsize) { resize(newsize, NodeTy()); }
480
481 };
482
483 namespace std {
484 // Ensure that swap uses the fast list swap...
485 template
486 void swap(iplist &Left, iplist &Right) {
487 Left.swap(Right);
488 }
489 } // End 'std' extensions...
490
491 #endif
117117 virtual const char *getPassName() const { return "Call Graph Construction"; }
118118
119119 // run - Compute the call graph for the specified module.
120 virtual bool run(Module *TheModule);
120 virtual bool run(Module &M);
121121
122122 // getAnalysisUsage - This obviously provides a call graph
123123 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
441441 virtual const char *getPassName() const { return "Data Structure Analysis"; }
442442
443443 // run - Do nothing, because methods are analyzed lazily
444 virtual bool run(Module *TheModule) { return false; }
444 virtual bool run(Module &TheModule) { return false; }
445445
446446 // getDSGraph - Return the data structure graph for the specified method.
447447 // Since method graphs are lazily computed, we may have to create one on the
441441 virtual const char *getPassName() const { return "Data Structure Analysis"; }
442442
443443 // run - Do nothing, because methods are analyzed lazily
444 virtual bool run(Module *TheModule) { return false; }
444 virtual bool run(Module &TheModule) { return false; }
445445
446446 // getDSGraph - Return the data structure graph for the specified method.
447447 // Since method graphs are lazily computed, we may have to create one on the
5252 private:
5353 DomSetMapType Doms;
5454
55 void calcForwardDominatorSet(Function *F);
56 void calcPostDominatorSet(Function *F);
55 void calcForwardDominatorSet(Function &F);
56 void calcPostDominatorSet(Function &F);
5757 public:
5858 // DominatorSet ctor - Build either the dominator set or the post-dominator
5959 // set for a function...
6868 else return "Dominator Set Construction";
6969 }
7070
71 virtual bool runOnFunction(Function *F);
71 virtual bool runOnFunction(Function &F);
7272
7373 // Accessor interface:
7474 typedef DomSetMapType::const_iterator const_iterator;
131131 else return "Immediate Dominators Construction";
132132 }
133133
134 virtual bool runOnFunction(Function *F) {
134 virtual bool runOnFunction(Function &F) {
135135 IDoms.clear(); // Reset from the last time we were run...
136136 DominatorSet *DS;
137137 if (isPostDominator())
227227 else return "Dominator Tree Construction";
228228 }
229229
230 virtual bool runOnFunction(Function *F) {
230 virtual bool runOnFunction(Function &F) {
231231 reset();
232232 DominatorSet *DS;
233233 if (isPostDominator())
288288 else return "Dominance Frontier Construction";
289289 }
290290
291 virtual bool runOnFunction(Function *) {
291 virtual bool runOnFunction(Function &) {
292292 Frontiers.clear();
293293 DominatorTree *DT;
294294 if (isPostDominator())
4040 // values of various types. If they are deemed to be 'unsafe' note that the
4141 // type is not safe to transform.
4242 //
43 virtual bool run(Module *M);
43 virtual bool run(Module &M);
4444
4545 // printResults - Loop over the results of the analysis, printing out unsafe
4646 // types.
5050 public:
5151 // run - This incorporates all types used by the specified module
5252 //
53 bool run(Module *M);
53 bool run(Module &M);
5454
5555 // getAnalysisUsage - Of course, we provide ourself...
5656 //
161161 public:
162162 // ctor - Create an instruction forest for the specified method...
163163 InstForest(Function *F) {
164 for (Function::iterator MI = F->begin(), ME = F->end(); MI != ME; ++MI) {
165 BasicBlock *BB = *MI;
166 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
167 Instruction *Inst = *I;
168 if (!getInstNode(Inst)) { // Do we already have a tree for this inst?
164 for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
165 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
166 if (!getInstNode(I)) { // Do we already have a tree for this inst?
169167 // No, create one! InstTreeNode ctor automatically adds the
170168 // created node into our InstMap
171 push_back(new InstTreeNode(*this, Inst, 0));
169 push_back(new InstTreeNode(*this, I, 0));
172170 }
173 }
174 }
175171 }
176172
177173 // dtor - Free the trees...
178174 ~InstForest() {
179 for (unsigned i = size(); i > 0; --i)
175 for (unsigned i = size(); i != 0; --i)
180176 delete operator[](i-1);
181177 }
182178
9292 IntervalIterator() {} // End iterator, empty stack
9393 IntervalIterator(Function *M, bool OwnMemory) : IOwnMem(OwnMemory) {
9494 OrigContainer = M;
95 if (!ProcessInterval(M->front())) {
95 if (!ProcessInterval(&M->front())) {
9696 assert(0 && "ProcessInterval should never fail for first interval!");
9797 }
9898 }
4141 const char *getPassName() const { return "Interval Partition Construction"; }
4242
4343 // run - Calculate the interval partition for this function
44 virtual bool runOnFunction(Function *F);
44 virtual bool runOnFunction(Function &F);
4545
4646 // IntervalPartition ctor - Build a reduced interval partition from an
4747 // existing interval graph. This takes an additional boolean parameter to
7878 // getLoopFor - Return the inner most loop that BB lives in. If a basic block
7979 // is in no loop (for example the entry node), null is returned.
8080 //
81 const Loop *getLoopFor(BasicBlock *BB) const {
82 std::map::const_iterator I = BBMap.find(BB);
81 const Loop *getLoopFor(const BasicBlock *BB) const {
82 std::map::const_iterator I=BBMap.find((BasicBlock*)BB);
8383 return I != BBMap.end() ? I->second : 0;
8484 }
85 inline const Loop *operator[](BasicBlock *BB) const {
85 inline const Loop *operator[](const BasicBlock *BB) const {
8686 return getLoopFor(BB);
8787 }
8888
8989 // getLoopDepth - Return the loop nesting level of the specified block...
90 unsigned getLoopDepth(BasicBlock *BB) const {
90 unsigned getLoopDepth(const BasicBlock *BB) const {
9191 const Loop *L = getLoopFor(BB);
9292 return L ? L->getLoopDepth() : 0;
9393 }
104104 #endif
105105
106106 // runOnFunction - Pass framework implementation
107 virtual bool runOnFunction(Function *F);
107 virtual bool runOnFunction(Function &F);
108108
109109 virtual void releaseMemory();
110110
2424 // verifyModule - Check a module for errors, printing messages on stderr.
2525 // Return true if the module is corrupt.
2626 //
27 bool verifyModule(const Module *M);
27 bool verifyModule(const Module &M);
2828
2929 // verifyFunction - Check a function for errors, useful for use when debugging a
3030 // pass.
31 bool verifyFunction(const Function *F);
31 bool verifyFunction(const Function &F);
3232
3333 #endif
2828 if (DeleteStream) delete Out;
2929 }
3030
31 bool run(Module *M) {
32 (*Out) << M;
31 bool run(Module &M) {
32 (*Out) << (Value&)M;
3333 return false;
3434 }
3535
5757 // runOnFunction - This pass just prints a banner followed by the function as
5858 // it's processed.
5959 //
60 bool runOnFunction(Function *F) {
61 (*Out) << Banner << (Value*)F;
60 bool runOnFunction(Function &F) {
61 (*Out) << Banner << (Value&)F;
6262 return false;
6363 }
6464
208208 // except that the root node is implicitly the first node of the function.
209209 //
210210 template <> struct GraphTraits : public GraphTraits {
211 static NodeType *getEntryNode(Function *F) { return F->getEntryNode(); }
211 static NodeType *getEntryNode(Function *F) { return &F->getEntryNode(); }
212212 };
213213 template <> struct GraphTraits :
214214 public GraphTraits {
215 static NodeType *getEntryNode(const Function *F) { return F->getEntryNode(); }
215 static NodeType *getEntryNode(const Function *F) { return &F->getEntryNode();}
216216 };
217217
218218
224224 template <> struct GraphTraits > :
225225 public GraphTraits > {
226226 static NodeType *getEntryNode(Inverse G) {
227 return G.Graph->front();
227 return &G.Graph->getEntryNode();
228228 }
229229 };
230230 template <> struct GraphTraits > :
231231 public GraphTraits > {
232232 static NodeType *getEntryNode(Inverse G) {
233 return G.Graph->front();
233 return &G.Graph->getEntryNode();
234234 }
235235 };
236236
77 #ifndef SUPPORT_CASTING_H
88 #define SUPPORT_CASTING_H
99
10 // real_type - Provide a macro to get the real type of a value that might be
11 // a use. This provides a typedef 'Type' that is the argument type for all
12 // non UseTy types, and is the contained pointer type of the use if it is a
13 // UseTy.
14 //
15 template class real_type { typedef X Type; };
16
17 //===----------------------------------------------------------------------===//
18 // Type Checking Templates
19 //===----------------------------------------------------------------------===//
10 #include
11
12 //===----------------------------------------------------------------------===//
13 // isa Support Templates
14 //===----------------------------------------------------------------------===//
15
16 template struct isa_impl_cl;
17
18 // Define a template that can be specialized by smart pointers to reflect the
19 // fact that they are automatically dereferenced, and are not involved with the
20 // template selection process... the default implementation is a noop.
21 //
22 template struct simplify_type {
23 typedef From SimpleType; // The real type this represents...
24
25 // An accessor to get the real value...
26 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
27 };
28
29 template struct simplify_type {
30 typedef const From SimpleType;
31 static SimpleType &getSimplifiedValue(const From &Val) {
32 return simplify_type::getSimplifiedValue((From&)Val);
33 }
34 };
35
2036
2137 // isa - Return true if the parameter to the template is an instance of the
2238 // template type argument. Used like this:
2339 //
24 // if (isa(myVal)) { ... }
25 //
26 template
27 inline bool isa(Y Val) {
28 assert(Val && "isa(NULL) invoked!");
29 return X::classof(Val);
30 }
40 // if (isa(myVal)) { ... }
41 //
42 template
43 inline bool isa_impl(const From &Val) {
44 return To::classof(&Val);
45 }
46
47 template
48 struct isa_impl_wrap {
49 // When From != SimplifiedType, we can simplify the type some more by using
50 // the simplify_type template.
51 static bool doit(const From &Val) {
52 return isa_impl_cl::template
53 isa(simplify_type::getSimplifiedValue(Val));
54 }
55 };
56
57 template
58 struct isa_impl_wrap {
59 // When From == SimpleType, we are as simple as we are going to get.
60 static bool doit(const FromTy &Val) {
61 return isa_impl(Val);
62 }
63 };
64
65 // isa_impl_cl - Use class partial specialization to transform types to a single
66 // cannonical form for isa_impl.
67 //
68 template
69 struct isa_impl_cl {
70 template
71 static bool isa(const FromCl &Val) {
72 return isa_impl_wrap
73 simplify_type::SimpleType>::doit(Val);
74 }
75 };
76
77 // Specialization used to strip const qualifiers off of the FromCl type...
78 template
79 struct isa_impl_cl {
80 template
81 static bool isa(const FromCl &Val) {
82 return isa_impl_cl::template isa(Val);
83 }
84 };
85
86 // Define pointer traits in terms of base traits...
87 template
88 struct isa_impl_cl {
89 template
90 static bool isa(FromCl *Val) {
91 return isa_impl_cl::template isa(*Val);
92 }
93 };
94
95 // Define reference traits in terms of base traits...
96 template
97 struct isa_impl_cl {
98 template
99 static bool isa(FromCl &Val) {
100 return isa_impl_cl::template isa(&Val);
101 }
102 };
103
104 template
105 inline bool isa(const Y &Val) {
106 return isa_impl_cl::template isa(Val);
107 }
108
109 //===----------------------------------------------------------------------===//
110 // cast Support Templates
111 //===----------------------------------------------------------------------===//
112
113 template struct cast_retty;
114
115
116 // Calculate what type the 'cast' function should return, based on a requested
117 // type of To and a source type of From.
118 template struct cast_retty_impl {
119 typedef To& ret_type; // Normal case, return Ty&
120 };
121 template struct cast_retty_impl {
122 typedef const To &ret_type; // Normal case, return Ty&
123 };
124
125 template struct cast_retty_impl {
126 typedef To* ret_type; // Pointer arg case, return Ty*
127 };
128
129 template struct cast_retty_impl {
130 typedef const To* ret_type; // Constant pointer arg case, return const Ty*
131 };
132
133 template struct cast_retty_impl {
134 typedef const To* ret_type; // Constant pointer arg case, return const Ty*
135 };
136
137
138 template
139 struct cast_retty_wrap {
140 // When the simplified type and the from type are not the same, use the type
141 // simplifier to reduce the type, then reuse cast_retty_impl to get the
142 // resultant type.
143 typedef typename cast_retty::ret_type ret_type;
144 };
145
146 template
147 struct cast_retty_wrap {
148 // When the simplified type is equal to the from type, use it directly.
149 typedef typename cast_retty_impl::ret_type ret_type;
150 };
151
152 template
153 struct cast_retty {
154 typedef typename cast_retty_wrap
155 simplify_type::SimpleType>::ret_type ret_type;
156 };
157
158 // Ensure the non-simple values are converted using the simplify_type template
159 // that may be specialized by smart pointers...
160 //
161 template struct cast_convert_val {
162 // This is not a simple type, use the template to simplify it...
163 static cast_retty::ret_type doit(const From &Val) {
164 return cast_convert_val
165 simplify_type::SimpleType>::doit(
166 simplify_type::getSimplifiedValue(Val));
167 }
168 };
169
170 template struct cast_convert_val {
171 // This _is_ a simple type, just cast it.
172 static cast_retty::ret_type doit(const FromTy &Val) {
173 return (cast_retty::ret_type)Val;
174 }
175 };
176
31177
32178
33179 // cast - Return the argument parameter cast to the specified type. This
35181 // on failure. But it will correctly return NULL when the input is NULL.
36182 // Used Like this:
37183 //
38 // cast< Instruction>(myVal)->getParent()
39 // cast(myVal)->getParent()
40 //
41 template
42 inline X *cast(Y Val) {
184 // cast(myVal)->getParent()
185 //
186 template
187 inline cast_retty::ret_type cast(const Y &Val) {
43188 assert(isa(Val) && "cast() argument of uncompatible type!");
44 return (X*)(real_type::Type)Val;
189 return cast_convert_val::SimpleType>::doit(Val);
45190 }
46191
47192 // cast_or_null - Functionally identical to cast, except that a null value is
48193 // accepted.
49194 //
50195 template
51 inline X *cast_or_null(Y Val) {
52 assert((Val == 0 || isa(Val)) &&
53 "cast_or_null() argument of uncompatible type!");
54 return (X*)(real_type::Type)Val;
196 inline cast_retty::ret_type cast_or_null(Y *Val) {
197 if (Val == 0) return 0;
198 assert(isa(Val) && "cast_or_null() argument of uncompatible type!");
199 return cast(Val);
55200 }
56201
57202
64209 //
65210
66211 template
67 inline X *dyn_cast(Y Val) {
68 return isa(Val) ? cast(Val) : 0;
212 inline cast_retty::ret_type dyn_cast(Y *Val) {
213 return isa(Val) ? cast(Val) : 0;
69214 }
70215
71216 // dyn_cast_or_null - Functionally identical to dyn_cast, except that a null
72217 // value is accepted.
73218 //
74219 template
75 inline X *dyn_cast_or_null(Y Val) {
76 return (Val && isa(Val)) ? cast(Val) : 0;
220 inline cast_retty::ret_type dyn_cast_or_null(Y *Val) {
221 return (Val && isa(Val)) ? cast(Val) : 0;
222 }
223
224
225 #ifdef DEBUG_CAST_OPERATORS
226 #include
227
228 struct bar {
229 bar() {}
230 private:
231 bar(const bar &);
232 };
233 struct foo {
234 void ext() const;
235 /* static bool classof(const bar *X) {
236 cerr << "Classof: " << X << "\n";
237 return true;
238 }*/
239 };
240
241 template <> inline bool isa_impl(const bar &Val) {
242 cerr << "Classof: " << &Val << "\n";
243 return true;
244 }
245
246
247 bar *fub();
248 void test(bar &B1, const bar *B2) {
249 // test various configurations of const
250 const bar &B3 = B1;
251 const bar *const B4 = B2;
252
253 // test isa
254 if (!isa(B1)) return;
255 if (!isa(B2)) return;
256 if (!isa(B3)) return;
257 if (!isa(B4)) return;
258
259 // test cast
260 foo &F1 = cast(B1);
261 const foo *F3 = cast(B2);
262 const foo *F4 = cast(B2);
263 const foo &F8 = cast(B3);
264 const foo *F9 = cast(B4);
265 foo *F10 = cast(fub());
266
267 // test cast_or_null
268 const foo *F11 = cast_or_null(B2);
269 const foo *F12 = cast_or_null(B2);
270 const foo *F13 = cast_or_null(B4);
271 const foo *F14 = cast_or_null(fub()); // Shouldn't print.
272
273 // These lines are errors...
274 //foo *F20 = cast(B2); // Yields const foo*
275 //foo &F21 = cast(B3); // Yields const foo&
276 //foo *F22 = cast(B4); // Yields const foo*
277 //foo &F23 = cast_or_null(B1);
278 //const foo &F24 = cast_or_null(B3);
279 }
280
281 bar *fub() { return 0; }
282 void main() {
283 bar B;
284 test(B, &B);
77285 }
78286
79287 #endif
288
289 #endif
3434 typedef IIty reference;
3535
3636 template InstIterator(M &m)
37 : BBs(m.getBasicBlocks()), BB(BBs.begin()) { // begin ctor
37 : BBs(m.getBasicBlockList()), BB(BBs.begin()) { // begin ctor
3838 if (BB != BBs.end()) {
39 BI = (*BB)->begin();
39 BI = BB->begin();
4040 advanceToNextBB();
4141 }
4242 }
4343
4444 template InstIterator(M &m, bool)
45 : BBs(m.getBasicBlocks()), BB(BBs.end()) { // end ctor
45 : BBs(m.getBasicBlockList()), BB(BBs.end()) { // end ctor
4646 }
4747
4848 // Accessors to get at the underlying iterators...
4949 inline BBIty &getBasicBlockIterator() { return BB; }
5050 inline BIty &getInstructionIterator() { return BI; }
5151
52 inline IIty operator*() const { return *BI; }
52 inline IIty operator*() const { return &*BI; }
5353 inline IIty operator->() const { return operator*(); }
5454
5555 inline bool operator==(const InstIterator &y) const {
6969 }
7070
7171 InstIterator& operator--() {
72 while (BB == BBs.end() || BI == (*BB)->begin()) {
72 while (BB == BBs.end() || BI == BB->begin()) {
7373 --BB;
74 BI = (*BB)->end();
74 BI = BB->end();
7575 }
7676 --BI;
7777 return *this;
8686 inline void advanceToNextBB() {
8787 // The only way that the II could be broken is if it is now pointing to
8888 // the end() of the current BasicBlock and there are successor BBs.
89 while (BI == (*BB)->end()) {
89 while (BI == BB->end()) {
9090 ++BB;
9191 if (BB == BBs.end()) break;
92 BI = (*BB)->begin();
92 BI = BB->begin();
9393 }
9494 }
9595 };
9696
9797
98 typedef InstIterator<ValueHolder>,
98 typedef InstIterator<iplist>,
9999 Function::iterator, BasicBlock::iterator,
100100 Instruction*> inst_iterator;
101 typedef InstIteratorValueHolder>,
101 typedef InstIteratoriplist>,
102102 Function::const_iterator,
103103 BasicBlock::const_iterator,
104104 const Instruction*> const_inst_iterator;
111111 inline const_inst_iterator inst_end(const Function *F) {
112112 return const_inst_iterator(*F, true);
113113 }
114 inline inst_iterator inst_begin(Function &F) { return inst_iterator(F); }
115 inline inst_iterator inst_end(Function &F) { return inst_iterator(F, true); }
116 inline const_inst_iterator inst_begin(const Function &F) {
117 return const_inst_iterator(F);
118 }
119 inline const_inst_iterator inst_end(const Function &F) {
120 return const_inst_iterator(F, true);
121 }
114122
115123 #endif
5656
5757
5858 #define DELEGATE(CLASS_TO_VISIT) \
59 return ((SubClass*)this)->visit##CLASS_TO_VISIT((CLASS_TO_VISIT*)I)
59 return ((SubClass*)this)->visit##CLASS_TO_VISIT((CLASS_TO_VISIT&)I)
6060
6161
6262 template
7777
7878 // Define visitors for modules, functions and basic blocks...
7979 //
80 void visit(Module *M) {
80 void visit(Module &M) {
8181 ((SubClass*)this)->visitModule(M);
82 visit(M->begin(), M->end());
82 visit(M.begin(), M.end());
8383 }
84 void visit(Function *F) {
84 void visit(Function &F) {
8585 ((SubClass*)this)->visitFunction(F);
86 visit(F->begin(), F->end());
86 visit(F.begin(), F.end());
8787 }
88 void visit(BasicBlock *BB) {
88 void visit(BasicBlock &BB) {
8989 ((SubClass*)this)->visitBasicBlock(BB);
90 visit(BB->begin(), BB->end());
90 visit(BB.begin(), BB.end());
9191 }
92
93 // Forwarding functions so that the user can visit with pointers AND refs.
94 void visit(Module *M) { visit(*M); }
95 void visit(Function *F) { visit(*F); }
96 void visit(BasicBlock *BB) { visit(*BB); }
97 RetTy visit(Instruction *I) { return visit(*I); }
9298
9399 // visit - Finally, code to visit an instruction...
94100 //
95 RetTy visit(Instruction *I) {
96 switch (I->getOpcode()) {
101 RetTy visit(Instruction &I) {
102 switch (I.getOpcode()) {
97103 // Build the switch statement using the Instruction.def file...
98104 #define HANDLE_INST(NUM, OPCODE, CLASS) \
99 case Instruction::OPCODE:return ((SubClass*)this)->visit##OPCODE((CLASS*)I);
105 case Instruction::OPCODE:return ((SubClass*)this)->visit##OPCODE((CLASS&)I);
100106 #include "llvm/Instruction.def"
101107
102108 default: assert(0 && "Unknown instruction type encountered!");
115121 // When visiting a module, function or basic block directly, these methods get
116122 // called to indicate when transitioning into a new unit.
117123 //
118 void visitModule (Module *M) {}
119 void visitFunction (Function *F) {}
120 void visitBasicBlock(BasicBlock *BB) {}
124 void visitModule (Module &M) {}
125 void visitFunction (Function &F) {}
126 void visitBasicBlock(BasicBlock &BB) {}
121127
122128
123129 // Define instruction specific visitor functions that can be overridden to
132138 // this, we do not autoexpand "Other" instructions, we do it manually.
133139 //
134140 #define HANDLE_INST(NUM, OPCODE, CLASS) \
135 RetTy visit##OPCODE(CLASS *I) { DELEGATE(CLASS); }
141 RetTy visit##OPCODE(CLASS &I) { DELEGATE(CLASS); }
136142 #define HANDLE_OTHER_INST(NUM, OPCODE, CLASS) // Ignore "other" instructions
137143 #include "llvm/Instruction.def"
138144
139145 // Implement all "other" instructions, except for PHINode
140 RetTy visitCast(CastInst *I) { DELEGATE(CastInst); }
141 RetTy visitCall(CallInst *I) { DELEGATE(CallInst); }
142 RetTy visitShr(ShiftInst *I) { DELEGATE(ShiftInst); }
143 RetTy visitShl(ShiftInst *I) { DELEGATE(ShiftInst); }
144 RetTy visitUserOp1(Instruction *I) { DELEGATE(Instruction); }
145 RetTy visitUserOp2(Instruction *I) { DELEGATE(Instruction); }
146 RetTy visitCast(CastInst &I) { DELEGATE(CastInst); }
147 RetTy visitCall(CallInst &I) { DELEGATE(CallInst); }
148 RetTy visitShr(ShiftInst &I) { DELEGATE(ShiftInst); }
149 RetTy visitShl(ShiftInst &I) { DELEGATE(ShiftInst); }
150 RetTy visitUserOp1(Instruction &I) { DELEGATE(Instruction); }
151 RetTy visitUserOp2(Instruction &I) { DELEGATE(Instruction); }
146152
147153
148154 // Specific Instruction type classes... note that all of the casts are
149155 // neccesary because we use the instruction classes as opaque types...
150156 //
151 RetTy visitReturnInst(ReturnInst *I) { DELEGATE(TerminatorInst);}
152 RetTy visitBranchInst(BranchInst *I) { DELEGATE(TerminatorInst);}
153 RetTy visitSwitchInst(SwitchInst *I) { DELEGATE(TerminatorInst);}
154 RetTy visitInvokeInst(InvokeInst *I) { DELEGATE(TerminatorInst);}
155 RetTy visitGenericUnaryInst(GenericUnaryInst *I) { DELEGATE(UnaryOperator); }
156 RetTy visitGenericBinaryInst(GenericBinaryInst *I){ DELEGATE(BinaryOperator);}
157 RetTy visitSetCondInst(SetCondInst *I) { DELEGATE(BinaryOperator);}
158 RetTy visitMallocInst(MallocInst *I) { DELEGATE(AllocationInst);}
159 RetTy visitAllocaInst(AllocaInst *I) { DELEGATE(AllocationInst);}
160 RetTy visitFreeInst(FreeInst *I) { DELEGATE(Instruction); }
161 RetTy visitLoadInst(LoadInst *I) { DELEGATE(MemAccessInst); }
162 RetTy visitStoreInst(StoreInst *I) { DELEGATE(MemAccessInst); }
163 RetTy visitGetElementPtrInst(GetElementPtrInst *I){ DELEGATE(MemAccessInst); }
164 RetTy visitPHINode(PHINode *I) { DELEGATE(Instruction); }
165 RetTy visitCastInst(CastInst *I) { DELEGATE(Instruction); }
166 RetTy visitCallInst(CallInst *I) { DELEGATE(Instruction); }
167 RetTy visitShiftInst(ShiftInst *I) { DELEGATE(Instruction); }
157 RetTy visitReturnInst(ReturnInst &I) { DELEGATE(TerminatorInst);}
158 RetTy visitBranchInst(BranchInst &I) { DELEGATE(TerminatorInst);}
159 RetTy visitSwitchInst(SwitchInst &I) { DELEGATE(TerminatorInst);}
160 RetTy visitInvokeInst(InvokeInst &I) { DELEGATE(TerminatorInst);}
161 RetTy visitGenericUnaryInst(GenericUnaryInst &I) { DELEGATE(UnaryOperator); }
162 RetTy visitGenericBinaryInst(GenericBinaryInst &I){ DELEGATE(BinaryOperator);}
163 RetTy visitSetCondInst(SetCondInst &I) { DELEGATE(BinaryOperator);}
164 RetTy visitMallocInst(MallocInst &I) { DELEGATE(AllocationInst);}
165 RetTy visitAllocaInst(AllocaInst &I) { DELEGATE(AllocationInst);}
166 RetTy visitFreeInst(FreeInst &I) { DELEGATE(Instruction); }
167 RetTy visitLoadInst(LoadInst &I) { DELEGATE(MemAccessInst); }
168 RetTy visitStoreInst(StoreInst &I) { DELEGATE(MemAccessInst); }
169 RetTy visitGetElementPtrInst(GetElementPtrInst &I){ DELEGATE(MemAccessInst); }
170 RetTy visitPHINode(PHINode &I) { DELEGATE(Instruction); }
171 RetTy visitCastInst(CastInst &I) { DELEGATE(Instruction); }
172 RetTy visitCallInst(CallInst &I) { DELEGATE(Instruction); }
173 RetTy visitShiftInst(ShiftInst &I) { DELEGATE(Instruction); }
168174
169175 // Next level propogators... if the user does not overload a specific
170176 // instruction type, they can overload one of these to get the whole class
171177 // of instructions...
172178 //
173 RetTy visitTerminatorInst(TerminatorInst *I) { DELEGATE(Instruction); }
174 RetTy visitUnaryOperator (UnaryOperator *I) { DELEGATE(Instruction); }
175 RetTy visitBinaryOperator(BinaryOperator *I) { DELEGATE(Instruction); }
176 RetTy visitAllocationInst(AllocationInst *I) { DELEGATE(Instruction); }
177 RetTy visitMemAccessInst (MemAccessInst *I) { DELEGATE(Instruction); }
179 RetTy visitTerminatorInst(TerminatorInst &I) { DELEGATE(Instruction); }
180 RetTy visitUnaryOperator (UnaryOperator &I) { DELEGATE(Instruction); }
181 RetTy visitBinaryOperator(BinaryOperator &I) { DELEGATE(Instruction); }
182 RetTy visitAllocationInst(AllocationInst &I) { DELEGATE(Instruction); }
183 RetTy visitMemAccessInst (MemAccessInst &I) { DELEGATE(Instruction); }
178184
179185 // If the user wants a 'default' case, they can choose to override this
180186 // function. If this function is not overloaded in the users subclass, then
182188 //
183189 // Note that you MUST override this function if your return type is not void.
184190 //
185 void visitInstruction(Instruction *I) {} // Ignore unhandled instructions
191 void visitInstruction(Instruction &I) {} // Ignore unhandled instructions
186192 };
187193
188194 #undef DELEGATE
5757 }
5858
5959 // run - do the transformation
60 virtual bool run(Module *M);
60 virtual bool run(Module &M);
6161
6262 protected:
6363
7575 // functions for functions than need to be copied because they have a new
7676 // signature type.
7777 //
78 void processGlobals(Module *M);
78 void processGlobals(Module &M);
7979
8080 // transformFunction - This transforms the instructions of the function to use
8181 // the new types.
8585 // removeDeadGlobals - This removes the old versions of functions that are no
8686 // longer needed.
8787 //
88 void removeDeadGlobals(Module *M);
88 void removeDeadGlobals(Module &M);
8989
9090 private:
9191 // ConvertType - Convert from the old type system to the new one...
9494 }
9595
9696 // Look for an indirect method call...
97 for (Function::iterator BBI = M->begin(), BBE = M->end(); BBI != BBE; ++BBI) {
98 BasicBlock *BB = *BBI;
97 for (Function::iterator BB = M->begin(), BBE = M->end(); BB != BBE; ++BB)
9998 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II){
100 Instruction *I = *II;
99 Instruction &I = *II;
101100
102 if (CallInst *CI = dyn_cast(I)) {
101 if (CallInst *CI = dyn_cast(&I)) {
103102 if (CI->getCalledFunction() == 0)
104103 Node->addCalledMethod(ExternalNode);
105 } else if (InvokeInst *II = dyn_cast(I)) {
104 } else if (InvokeInst *II = dyn_cast(&I)) {
106105 if (II->getCalledFunction() == 0)
107106 Node->addCalledMethod(ExternalNode);
108107 }
109108 }
110 }
111109 }
112110
113 bool CallGraph::run(Module *TheModule) {
111 bool CallGraph::run(Module &M) {
114112 destroy();
115113
116 Mod = TheModule;
114 Mod = &M;
117115 ExternalNode = getNodeFor(0);
118116 Root = 0;
119117
120118 // Add every method to the call graph...
121 for_each(Mod->begin(), Mod->end(), bind_obj(this,&CallGraph::addToCallGraph));
119 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
120 addToCallGraph(I);
122121
123122 // If we didn't find a main method, use the external call graph node
124123 if (Root == 0) Root = ExternalNode;
1818 #include "llvm/Analysis/FindUnsafePointerTypes.h"
1919 #include "llvm/Assembly/CachedWriter.h"
2020 #include "llvm/Type.h"
21 #include "llvm/Instruction.h"
2221 #include "llvm/Module.h"
2322 #include "llvm/Support/InstIterator.h"
2423 #include "Support/CommandLine.h"
4948 }
5049
5150
52 bool FindUnsafePointerTypes::run(Module *Mod) {
53 for (Module::iterator MI = Mod->begin(), ME = Mod->end();
54 MI != ME; ++MI) {
55 const Function *M = *MI; // We don't need/want write access
56 for (const_inst_iterator I = inst_begin(M), E = inst_end(M); I != E; ++I) {
57 const Instruction *Inst = *I;
58 const Type *ITy = Inst->getType();
51 bool FindUnsafePointerTypes::run(Module &Mod) {
52 for (Module::iterator FI = Mod.begin(), E = Mod.end();
53 FI != E; ++FI) {
54 const Function *F = FI; // We don't need/want write access
55 for (const_inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
56 const Type *ITy = I->getType();
5957 if (isa(ITy) && !UnsafeTypes.count((PointerType*)ITy))
60 if (!isSafeInstruction(Inst)) {
58 if (!isSafeInstruction(*I)) {
6159 UnsafeTypes.insert((PointerType*)ITy);
6260
6361 if (PrintFailures) {
64 CachedWriter CW(M->getParent(), std::cerr);
62 CachedWriter CW(F->getParent(), std::cerr);
6563 CW << "FindUnsafePointerTypes: Type '" << ITy
66 << "' marked unsafe in '" << M->getName() << "' by:\n" << Inst;
64 << "' marked unsafe in '" << F->getName() << "' by:\n" << **I;
6765 }
6866 }
6967 }
66 #include "llvm/Analysis/FindUsedTypes.h"
77 #include "llvm/Assembly/CachedWriter.h"
88 #include "llvm/SymbolTable.h"
9 #include "llvm/GlobalVariable.h"
109 #include "llvm/DerivedTypes.h"
1110 #include "llvm/Module.h"
12 #include "llvm/Instruction.h"
1311 #include "llvm/Support/InstIterator.h"
1412
1513 AnalysisID FindUsedTypes::ID(AnalysisID::create());
4139
4240 // run - This incorporates all types used by the specified module
4341 //
44 bool FindUsedTypes::run(Module *m) {
42 bool FindUsedTypes::run(Module &m) {
4543 UsedTypes.clear(); // reset if run multiple times...
4644
47 if (IncludeSymbolTables && m->hasSymbolTable())
48 IncorporateSymbolTable(m->getSymbolTable()); // Add symtab first...
45 if (IncludeSymbolTables && m.hasSymbolTable())
46 IncorporateSymbolTable(m.getSymbolTable()); // Add symtab first...
4947
5048 // Loop over global variables, incorporating their types
51 for (Module::const_giterator I = m->gbegin(), E = m->gend(); I != E; ++I)
52 IncorporateType((*I)->getType());
49 for (Module::const_giterator I = m.gbegin(), E = m.gend(); I != E; ++I)
50 IncorporateType(I->getType());
5351
54 for (Module::iterator MI = m->begin(), ME = m->end(); MI != ME; ++MI) {
55 const Function *M = *MI;
56 if (IncludeSymbolTables && M->hasSymbolTable())
57 IncorporateSymbolTable(M->getSymbolTable()); // Add symtab first...
52 for (Module::iterator MI = m.begin(), ME = m.end(); MI != ME; ++MI) {
53 const Function &F = *MI;
54 if (IncludeSymbolTables && F.hasSymbolTable())
55 IncorporateSymbolTable(F.getSymbolTable()); // Add symtab first...
5856
5957 // Loop over all of the instructions in the function, adding their return
6058 // type as well as the types of their operands.
6159 //
62 for (const_inst_iterator II = inst_begin(M), IE = inst_end(M);
60 for (const_inst_iterator II = inst_begin(F), IE = inst_end(F);
6361 II != IE; ++II) {
6462 const Instruction *I = *II;
6563 const Type *Ty = I->getType();
3030 if (isa(V) || isa(V) || isa(V))
3131 return true;
3232
33 Instruction *I = cast(V);
34 BasicBlock *BB = I->getParent();
33 const Instruction *I = cast(V);
34 const BasicBlock *BB = I->getParent();
3535
3636 return !L->contains(BB);
3737 }
4040 InductionVariable::Classify(const Value *Start, const Value *Step,
4141 const Loop *L = 0) {
4242 // Check for cannonical and simple linear expressions now...
43 if (ConstantInt *CStart = dyn_cast(Start))
44 if (ConstantInt *CStep = dyn_cast(Step)) {
43 if (const ConstantInt *CStart = dyn_cast(Start))
44 if (const ConstantInt *CStep = dyn_cast(Step)) {
4545 if (CStart->equalsInt(0) && CStep->equalsInt(1))
4646 return Cannonical;
4747 else
5050 // IntervalPartition ctor - Build the first level interval partition for the
5151 // specified function...
5252 //
53 bool IntervalPartition::runOnFunction(Function *F) {
54 assert(F->front() && "Cannot operate on prototypes!");
55
53 bool IntervalPartition::runOnFunction(Function &F) {
5654 // Pass false to intervals_begin because we take ownership of it's memory
57 function_interval_iterator I = intervals_begin(F, false);
58 assert(I != intervals_end(F) && "No intervals in function!?!?!");
55 function_interval_iterator I = intervals_begin(&F, false);
56 assert(I != intervals_end(&F) && "No intervals in function!?!?!");
5957
6058 addIntervalToPartition(RootInterval = *I);
6159
6260 ++I; // After the first one...
6361
6462 // Add the rest of the intervals to the partition...
65 for_each(I, intervals_end(F),
63 for_each(I, intervals_end(&F),
6664 bind_obj(this, &IntervalPartition::addIntervalToPartition));
6765
6866 // Now that we know all of the successor information, propogate this to the
3434 //===----------------------------------------------------------------------===//
3535 // LoopInfo implementation
3636 //
37 bool LoopInfo::runOnFunction(Function *F) {
37 bool LoopInfo::runOnFunction(Function &) {
3838 releaseMemory();
3939 Calculate(getAnalysis()); // Update
4040 return false;
2020 AnalysisID DominatorSet::ID(AnalysisID::create(), true);
2121 AnalysisID DominatorSet::PostDomID(AnalysisID::create(), true);
2222
23 bool DominatorSet::runOnFunction(Function *F) {
23 bool DominatorSet::runOnFunction(Function &F) {
2424 Doms.clear(); // Reset from the last time we were run...
2525
2626 if (isPostDominator())
3939
4040 // Loop through the basic block until we find A or B.
4141 BasicBlock::iterator I = BBA->begin();
42 for (; *I != A && *I != B; ++I) /*empty*/;
42 for (; &*I != A && &*I != B; ++I) /*empty*/;
4343
4444 // A dominates B if it is found first in the basic block...
45 return *I == A;
45 return &*I == A;
4646 }
4747
4848 // calcForwardDominatorSet - This method calculates the forward dominator sets
4949 // for the specified function.
5050 //
51 void DominatorSet::calcForwardDominatorSet(Function *M) {
52 Root = M->getEntryNode();
51 void DominatorSet::calcForwardDominatorSet(Function &F) {
52 Root = &F.getEntryNode();
5353 assert(pred_begin(Root) == pred_end(Root) &&
5454 "Root node has predecessors in function!");
5555
5858 Changed = false;
5959
6060 DomSetType WorkingSet;
61 df_iterator It = df_begin(M), End = df_end(M);
61 df_iterator It = df_begin(&F), End = df_end(&F);
6262 for ( ; It != End; ++It) {
6363 BasicBlock *BB = *It;
6464 pred_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
9292 // only have a single exit node (return stmt), then calculates the post
9393 // dominance sets for the function.
9494 //
95 void DominatorSet::calcPostDominatorSet(Function *F) {
95 void DominatorSet::calcPostDominatorSet(Function &F) {
9696 // Since we require that the unify all exit nodes pass has been run, we know
9797 // that there can be at most one return instruction in the function left.
9898 // Get it.
100100 Root = getAnalysis().getExitNode();
101101
102102 if (Root == 0) { // No exit node for the function? Postdomsets are all empty
103 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
104 Doms[*FI] = DomSetType();
103 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
104 Doms[FI] = DomSetType();
105105 return;
106106 }
107107
3333 fclose(F);
3434
3535 if (Result) { // Check to see that it is valid...
36 if (verifyModule(Result)) {
36 if (verifyModule(*Result)) {
3737 delete Result;
3838 throw ParseException(Filename, "Source file is not well formed LLVM!");
3939 }
4444 #define UR_OUT(X)
4545 #endif
4646
47 // This contains info used when building the body of a method. It is destroyed
48 // when the method is completed.
47 // This contains info used when building the body of a function. It is
48 // destroyed when the function is completed.
4949 //
5050 typedef vector ValueList; // Numbered defs
5151 static void ResolveDefinitions(vector &LateResolvers,
6767 GlobalRefsType GlobalRefs;
6868
6969 void ModuleDone() {
70 // If we could not resolve some methods at method compilation time (calls to
71 // methods before they are defined), resolve them now... Types are resolved
72 // when the constant pool has been completely parsed.
70 // If we could not resolve some functions at function compilation time
71 // (calls to functions before they are defined), resolve them now... Types
72 // are resolved when the constant pool has been completely parsed.
7373 //
7474 ResolveDefinitions(LateResolveValues);
7575
8787 ThrowException(UndefinedReferences);
8888 }
8989
90 Values.clear(); // Clear out method local definitions
90 Values.clear(); // Clear out function local definitions
9191 Types.clear();
9292 CurrentModule = 0;
9393 }
131131 } CurModule;
132132
133133 static struct PerFunctionInfo {
134 Function *CurrentFunction; // Pointer to current method being created
134 Function *CurrentFunction; // Pointer to current function being created
135135
136136 vector Values; // Keep track of numbered definitions
137137 vector LateResolveValues;
138138 vector Types;
139139 map LateResolveTypes;
140 bool isDeclare; // Is this method a forward declararation?
140 bool isDeclare; // Is this function a forward declararation?
141141
142142 inline PerFunctionInfo() {
143143 CurrentFunction = 0;
155155 // resolve the branches now...
156156 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
157157
158 Values.clear(); // Clear out method local definitions
158 Values.clear(); // Clear out function local definitions
159159 Types.clear();
160160 CurrentFunction = 0;
161161 isDeclare = false;
162162 }
163 } CurMeth; // Info for the current method...
163 } CurMeth; // Info for the current function...
164164
165165 static bool inFunctionScope() { return CurMeth.CurrentFunction != 0; }
166166
209209 Value *N = SymTab ? SymTab->lookup(Type::TypeTy, Name) : 0;
210210
211211 if (N == 0) {
212 // Symbol table doesn't automatically chain yet... because the method
212 // Symbol table doesn't automatically chain yet... because the function
213213 // hasn't been added to the module...
214214 //
215215 SymTab = CurModule.CurrentModule->getSymbolTable();
740740
741741 //===----------------------------------------------------------------------===//
742742 // Types includes all predefined types... except void, because it can only be
743 // used in specific contexts (method returning void for example). To have
743 // used in specific contexts (function returning void for example). To have
744744 // access to it, a user must explicitly use TypesV.
745745 //
746746
809809 delete $1;
810810 };
811811
812 // TypeList - Used for struct declarations and as a basis for method type
812 // TypeList - Used for struct declarations and as a basis for function type
813813 // declaration type lists
814814 //
815815 TypeListI : UpRTypes {
820820 ($$=$1)->push_back(*$3); delete $3;
821821 };
822822
823 // ArgTypeList - List of types for a method type declaration...
823 // ArgTypeList - List of types for a function type declaration...
824824 ArgTypeListI : TypeListI
825825 | TypeListI ',' DOTDOTDOT {
826826 ($$=$1)->push_back(Type::VoidTy);
10101010 CurModule.ModuleDone();
10111011 };
10121012
1013 // FunctionList - A list of methods, preceeded by a constant pool.
1013 // FunctionList - A list of functions, preceeded by a constant pool.
10141014 //
10151015 FunctionList : FunctionList Function {
10161016 $$ = $1;
11631163 // Yes it is. If this is the case, either we need to be a forward decl,
11641164 // or it needs to be.
11651165 if (!CurMeth.isDeclare && !M->isExternal())
1166 ThrowException("Redefinition of method '" + FunctionName + "'!");
1167
1168 // If we found a preexisting method prototype, remove it from the module,
1169 // so that we don't get spurious conflicts with global & local variables.
1166 ThrowException("Redefinition of function '" + FunctionName + "'!");
1167
1168 // If we found a preexisting function prototype, remove it from the
1169 // module, so that we don't get spurious conflicts with global & local
1170 // variables.
11701171 //
11711172 CurModule.CurrentModule->getFunctionList().remove(M);
11721173 }
11811182
11821183 CurMeth.FunctionStart(M);
11831184
1184 // Add all of the arguments we parsed to the method...
1185 // Add all of the arguments we parsed to the function...
11851186 if ($5 && !CurMeth.isDeclare) { // Is null if empty...
1186 Function::ArgumentListType &ArgList = M->getArgumentList();
1187
11881187 for (list >::iterator I = $5->begin();
11891188 I != $5->end(); ++I) {
11901189 if (setValueName(I->first, I->second)) { // Insert into symtab...
11921191 }
11931192
11941193 InsertValue(I->first);
1195 ArgList.push_back(I->first);
1194 M->getArgumentList().push_back(I->first);
11961195 }
11971196 delete $5; // We're now done with the argument list
11981197 } else if ($5) {
12111210 FunctionHeader : FunctionHeaderH BEGIN {
12121211 $$ = CurMeth.CurrentFunction;
12131212
1214 // Resolve circular types before we parse the body of the method.
1213 // Resolve circular types before we parse the body of the function.
12151214 ResolveTypes(CurMeth.LateResolveTypes);
12161215 };
12171216
12741273
12751274
12761275 BasicBlockList : BasicBlockList BasicBlock {
1277 ($$ = $1)->getBasicBlocks().push_back($2);
1278 }
1279 | FunctionHeader BasicBlock { // Do not allow methods with 0 basic blocks
1280 ($$ = $1)->getBasicBlocks().push_back($2);
1276 ($$ = $1)->getBasicBlockList().push_back($2);
1277 }
1278 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
1279 ($$ = $1)->getBasicBlockList().push_back($2);
12811280 };
12821281
12831282
13571356 }
13581357 delete $2;
13591358
1360 Value *V = getVal(PMTy, $3); // Get the method we're calling...
1359 Value *V = getVal(PMTy, $3); // Get the function we're calling...
13611360
13621361 BasicBlock *Normal = dyn_cast($8);
13631362 BasicBlock *Except = dyn_cast($10);
14931492 }
14941493 delete $2;
14951494
1496 Value *V = getVal(PMTy, $3); // Get the method we're calling...
1495 Value *V = getVal(PMTy, $3); // Get the function we're calling...
14971496
14981497 // Create the call node...
14991498 if (!$5) { // Has no arguments?
1010
1111 #include "llvm/SlotCalculator.h"
1212 #include "llvm/Analysis/ConstantsScanner.h"
13 #include "llvm/Function.h"
14 #include "llvm/GlobalVariable.h"
1513 #include "llvm/Module.h"
16 #include "llvm/BasicBlock.h"
1714 #include "llvm/iOther.h"
1815 #include "llvm/Constant.h"
1916 #include "llvm/DerivedTypes.h"
2017 #include "llvm/SymbolTable.h"
21 #include "llvm/Argument.h"
2218 #include "Support/DepthFirstIterator.h"
2319 #include "Support/STLExtras.h"
2420 #include
7470 //
7571 for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
7672 I != E; ++I) {
77 if ((*I)->hasInitializer())
78 insertValue((*I)->getInitializer());
73 if (I->hasInitializer())
74 insertValue(I->getInitializer());
7975 }
8076
8177 // Add all of the global variables to the value table...
8278 //
83 for_each(TheModule->gbegin(), TheModule->gend(),
84 bind_obj(this, &SlotCalculator::insertValue));
79 for(Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
80 I != E; ++I)
81 insertValue(I);
8582
8683 // Scavenge the types out of the functions, then add the functions themselves
8784 // to the value table...
8885 //
89 for_each(TheModule->begin(), TheModule->end(), // Insert functions...
90 bind_obj(this, &SlotCalculator::insertValue));
86 for(Module::const_iterator I = TheModule->begin(), E = TheModule->end();
87 I != E; ++I)
88 insertValue(I);
9189
9290 // Insert constants that are named at module level into the slot pool so that
9391 // the module symbol table can refer to them...
131129 SC_DEBUG("Inserting function arguments\n");
132130
133131 // Iterate over function arguments, adding them to the value table...
134 for_each(M->getArgumentList().begin(), M->getArgumentList().end(),
135 bind_obj(this, &SlotCalculator::insertValue));
132 for(Function::const_aiterator I = M->abegin(), E = M->aend(); I != E; ++I)
133 insertValue(I);
136134
137135 // Iterate over all of the instructions in the function, looking for constant
138136 // values that are referenced. Add these to the value pools before any
165163 SC_DEBUG("Inserting Labels:\n");
166164
167165 // Iterate over basic blocks, adding them to the value table...
168 for_each(M->begin(), M->end(),
169 bind_obj(this, &SlotCalculator::insertValue));
166 for (Function::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
167 insertValue(I);
168 /* for_each(M->begin(), M->end(),
169 bind_obj(this, &SlotCalculator::insertValue));*/
170170
171171 SC_DEBUG("Inserting Instructions:\n");
172172
14881488 AU.addRequired(FunctionLiveVarInfo::ID);
14891489 }
14901490
1491 bool runOnFunction(Function *F);
1491 bool runOnFunction(Function &F);
14921492 };
14931493 } // end anonymous namespace
14941494
14951495
1496 bool
1497 InstructionSchedulingWithSSA::runOnFunction(Function *M)
1496 bool InstructionSchedulingWithSSA::runOnFunction(Function &F)
14981497 {
14991498 if (SchedDebugLevel == Sched_Disable)
15001499 return false;
15011500
1502 SchedGraphSet graphSet(M, target);
1501 SchedGraphSet graphSet(&F, target);
15031502
15041503 if (SchedDebugLevel >= Sched_PrintSchedGraphs)
15051504 {
15191518 cerr << "\n*** TRACE OF INSTRUCTION SCHEDULING OPERATIONS\n\n";
15201519
15211520 // expensive!
1522 SchedPriorities schedPrio(M, graph,getAnalysis());
1521 SchedPriorities schedPrio(&F, graph,getAnalysis());
15231522 SchedulingManager S(target, graph, schedPrio);
15241523
15251524 ChooseInstructionsForDelaySlots(S, bb, graph); // modifies graph
15321531 if (SchedDebugLevel >= Sched_PrintMachineCode)
15331532 {
15341533 cerr << "\n*** Machine instructions after INSTRUCTION SCHEDULING\n";
1535 MachineCodeForMethod::get(M).dump();
1534 MachineCodeForMethod::get(&F).dump();
15361535 }
15371536
15381537 return false;
984984 const TargetMachine& target)
985985 {
986986 for (Function::const_iterator BI = F->begin(); BI != F->end(); ++BI)
987 addGraph(new SchedGraph(*BI, target));
987 addGraph(new SchedGraph(BI, target));
988988 }
989989
990990
8383
8484 // first find the live ranges for all incoming args of the function since
8585 // those LRs start from the start of the function
86
87 // get the argument list
88 const Function::ArgumentListType& ArgList = Meth->getArgumentList();
89
90 Function::ArgumentListType::const_iterator ArgIt = ArgList.begin();
91 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
92 LiveRange * ArgRange = new LiveRange(); // creates a new LR and
93 const Value *Val = (const Value *) *ArgIt;
94
95 ArgRange->insert(Val); // add the arg (def) to it
96 LiveRangeMap[Val] = ArgRange;
86 for (Function::const_aiterator AI = Meth->abegin(); AI != Meth->aend(); ++AI){
87 LiveRange *ArgRange = new LiveRange(); // creates a new LR and
88 ArgRange->insert(AI); // add the arg (def) to it
89 LiveRangeMap[AI] = ArgRange;
9790
9891 // create a temp machine op to find the register class of value
9992 //const MachineOperand Op(MachineOperand::MO_VirtualRegister);
10093
101 unsigned rcid = MRI.getRegClassIDOfValue( Val );
102 ArgRange->setRegClass(RegClassList[ rcid ] );
94 unsigned rcid = MRI.getRegClassIDOfValue(AI);
95 ArgRange->setRegClass(RegClassList[rcid]);
10396
10497
105 if( DEBUG_RA > 1) {
106 cerr << " adding LiveRange for argument "
107 << RAV((const Value *)*ArgIt) << "\n";
108 }
98 if( DEBUG_RA > 1)
99 cerr << " adding LiveRange for argument " << RAV(AI) << "\n";
109100 }
110101
111102 // Now suggest hardware registers for these function args
122113 // the same Value in machine instructions.
123114
124115 // get the iterator for machine instructions
125 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
116 const MachineCodeForBasicBlock& MIVec = BBI->getMachineInstrVec();
126117
127118 // iterate over all the machine instructions in BB
128119 for(MachineCodeForBasicBlock::const_iterator MInstIterator = MIVec.begin();
274265 BBI != BBE; ++BBI) {
275266
276267 // get the iterator for machine instructions
277 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
268 const MachineCodeForBasicBlock& MIVec = BBI->getMachineInstrVec();
278269 MachineCodeForBasicBlock::const_iterator MInstIterator = MIVec.begin();
279270
280271 // iterate over all the machine instructions in BB
4848
4949 const char *getPassName() const { return "Register Allocation"; }
5050
51 bool runOnFunction(Function *F) {
51 bool runOnFunction(Function &F) {
5252 if (DEBUG_RA)
53 cerr << "\n******************** Function "<< F->getName()
54 << " ********************\n";
53 cerr << "\n********* Function "<< F.getName() << " ***********\n";
5554
56 PhyRegAlloc PRA(F, Target, &getAnalysis(),
55 PhyRegAlloc PRA(&F, Target, &getAnalysis(),
5756 &getAnalysis());
5857 PRA.allocateRegisters();
5958
8685
8786 // create each RegisterClass and put in RegClassList
8887 //
89 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
88 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
9089 RegClassList.push_back(new RegClass(F, MRI.getMachineRegClass(rc),
9190 &ResColList));
9291 }
9695 // Destructor: Deletes register classes
9796 //----------------------------------------------------------------------------
9897 PhyRegAlloc::~PhyRegAlloc() {
99 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
98 for ( unsigned rc=0; rc < NumOfRegClasses; rc++)
10099 delete RegClassList[rc];
101100
102101 AddedInstrMap.clear();
119118 if (HMI->first) {
120119 LiveRange *L = HMI->second; // get the LiveRange
121120 if (!L) {
122 if( DEBUG_RA) {
121 if (DEBUG_RA) {
123122 cerr << "\n*?!?Warning: Null liver range found for: "
124123 << RAV(HMI->first) << "\n";
125124 }
127126 }
128127 // if the Value * is not null, and LR
129128 // is not yet written to the IGNodeList
130 if( !(L->getUserIGNode()) ) {
129 if (!(L->getUserIGNode()) ) {
131130 RegClass *const RC = // RegClass of first value in the LR
132131 RegClassList[ L->getRegClass()->getID() ];
133132
137136 }
138137
139138 // init RegClassList
140 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
139 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
141140 RegClassList[rc]->createInterferenceGraph();
142141
143 if( DEBUG_RA)
142 if (DEBUG_RA)
144143 cerr << "LRLists Created!\n";
145144 }
146145
170169
171170 // for each live var in live variable set
172171 //
173 for( ; LIt != LVSet->end(); ++LIt) {
172 for ( ; LIt != LVSet->end(); ++LIt) {
174173
175174 if (DEBUG_RA > 1)
176175 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
183182 // doesn't have a dominating def - see Assumptions above
184183 //
185184 if (LROfVar) {
186 if(LROfDef == LROfVar) // do not set interf for same LR
185 if (LROfDef == LROfVar) // do not set interf for same LR
187186 continue;
188187
189188 // if 2 reg classes are the same set interference
211210 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
212211 const ValueSet *LVSetAft) {
213212
214 if( DEBUG_RA)
213 if (DEBUG_RA)
215214 cerr << "\n For call inst: " << *MInst;
216215
217216 ValueSet::const_iterator LIt = LVSetAft->begin();
218217
219218 // for each live var in live variable set after machine inst
220219 //
221 for( ; LIt != LVSetAft->end(); ++LIt) {
220 for ( ; LIt != LVSetAft->end(); ++LIt) {
222221
223222 // get the live range corresponding to live var
224223 //
225224 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
226225
227 if( LR && DEBUG_RA) {
226 if (LR && DEBUG_RA) {
228227 cerr << "\n\tLR Aft Call: ";
229228 printSet(*LR);
230229 }
232231 // LR can be null if it is a const since a const
233232 // doesn't have a dominating def - see Assumptions above
234233 //
235 if( LR ) {
234 if (LR ) {
236235 LR->setCallInterference();
237 if( DEBUG_RA) {
236 if (DEBUG_RA) {
238237 cerr << "\n ++Added call interf for LR: " ;
239238 printSet(*LR);
240239 }
258257
259258 // If the CALL is an indirect call, find the LR of the function pointer.
260259 // That has a call interference because it conflicts with outgoing args.
261 if( const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
260 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
262261 LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
263262 assert( AddrValLR && "No LR for indirect addr val of call");
264263 AddrValLR->setCallInterference();
277276 void PhyRegAlloc::buildInterferenceGraphs()
278277 {
279278
280 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
279 if (DEBUG_RA) cerr << "Creating interference graphs ...\n";
281280
282281 unsigned BBLoopDepthCost;
283282 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
285284
286285 // find the 10^(loop_depth) of this BB
287286 //
288 BBLoopDepthCost = (unsigned) pow(10.0, LoopDepthCalc->getLoopDepth(*BBI));
287 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BBI));
289288
290289 // get the iterator for machine instructions
291290 //
292 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
291 const MachineCodeForBasicBlock& MIVec = BBI->getMachineInstrVec();
293292 MachineCodeForBasicBlock::const_iterator MII = MIVec.begin();
294293
295294 // iterate over all the machine instructions in BB
296295 //
297 for( ; MII != MIVec.end(); ++MII) {
296 for ( ; MII != MIVec.end(); ++MII) {
298297
299298 const MachineInstr *MInst = *MII;
300299
301300 // get the LV set after the instruction
302301 //
303 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, *BBI);
302 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BBI);
304303
305304 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
306305
307 if( isCallInst ) {
306 if (isCallInst ) {
308307 // set the isCallInterference flag of each live range wich extends
309308 // accross this call instruction. This information is used by graph
310309 // coloring algo to avoid allocating volatile colors to live ranges
338337 // instr (currently, only calls have this).
339338 //
340339 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
341 if( NumOfImpRefs > 0 ) {
342 for(unsigned z=0; z < NumOfImpRefs; z++)
343 if( MInst->implicitRefIsDefined(z) )
340 if ( NumOfImpRefs > 0 ) {
341 for (unsigned z=0; z < NumOfImpRefs; z++)
342 if (MInst->implicitRefIsDefined(z) )
344343 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
345344 }
346345
354353 //
355354 addInterferencesForArgs();
356355
357 if( DEBUG_RA)
356 if (DEBUG_RA)
358357 cerr << "Interference graphs calculted!\n";
359358
360359 }
379378 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
380379
381380 MachineInstr::const_val_op_iterator It2 = It1;
382 for(++It2; It2 != ItE; ++It2) {
381 for (++It2; It2 != ItE; ++It2) {
383382 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
384383
385384 if (LROfOp2) {
386385 RegClass *RCOfOp1 = LROfOp1->getRegClass();
387386 RegClass *RCOfOp2 = LROfOp2->getRegClass();
388387
389 if( RCOfOp1 == RCOfOp2 ){
388 if (RCOfOp1 == RCOfOp2 ){
390389 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
391390 setInterf = true;
392391 }
408407 //----------------------------------------------------------------------------
409408 void PhyRegAlloc::addInterferencesForArgs() {
410409 // get the InSet of root BB
411 const ValueSet &InSet = LVI->getInSetOfBB(Meth->front());
412
413 // get the argument list
414 const Function::ArgumentListType &ArgList = Meth->getArgumentList();
415
416 // get an iterator to arg list
417 Function::ArgumentListType::const_iterator ArgIt = ArgList.begin();
418
419
420 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
421 addInterference((Value*)*ArgIt, &InSet, false);// add interferences between
422 // args and LVars at start
423 if( DEBUG_RA > 1)
424 cerr << " - %% adding interference for argument "
425 << RAV((const Value *)*ArgIt) << "\n";
410 const ValueSet &InSet = LVI->getInSetOfBB(&Meth->front());
411
412 for (Function::const_aiterator AI = Meth->abegin(); AI != Meth->aend(); ++AI) {
413 // add interferences between args and LVars at start
414 addInterference(AI, &InSet, false);
415
416 if (DEBUG_RA > 1)
417 cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
426418 }
427419 }
428420
471463 {
472464 MachineInstr* OrigMI = *MII;
473465 std::vector::iterator AdIt;
474 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
466 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
475467 {
476 if(DEBUG_RA) {
468 if (DEBUG_RA) {
477469 if (OrigMI) cerr << "For MInst: " << *OrigMI;
478470 cerr << msg << " APPENDed instr: " << **AdIt << "\n";
479471 }
486478
487479 void PhyRegAlloc::updateMachineCode()
488480 {
489 const BasicBlock* entryBB = Meth->getEntryNode();
490 if (entryBB) {
491 MachineCodeForBasicBlock& MIVec = entryBB->getMachineInstrVec();
492 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
493
494 // Insert any instructions needed at method entry
495 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MIVec, MII,
496 "At function entry: \n");
497 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
498 "InstrsAfter should be unnecessary since we are just inserting at "
499 "the function entry point here.");
500 }
481 MachineCodeForBasicBlock& MIVec = Meth->getEntryNode().getMachineInstrVec();
482
483 // Insert any instructions needed at method entry
484 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
485 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MIVec, MII,
486 "At function entry: \n");
487 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
488 "InstrsAfter should be unnecessary since we are just inserting at "
489 "the function entry point here.");
501490
502491 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
503492 BBI != BBE; ++BBI) {
504493
505494 // iterate over all the machine instructions in BB
506 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
507 for(MachineCodeForBasicBlock::iterator MII = MIVec.begin();
495 MachineCodeForBasicBlock &MIVec = BBI->getMachineInstrVec();
496 for (MachineCodeForBasicBlock::iterator MII = MIVec.begin();
508497 MII != MIVec.end(); ++MII) {
509498
510499 MachineInstr *MInst = *MII;
529518 mcInfo.popAllTempValues(TM);
530519
531520 if (TM.getInstrInfo().isCall(Opcode))
532 MRI.colorCallArgs(MInst, LRI, &AI, *this, *BBI);
521 MRI.colorCallArgs(MInst, LRI, &AI, *this, BBI);
533522 else if (TM.getInstrInfo().isReturn(Opcode))
534523 MRI.colorRetValue(MInst, LRI, &AI);
535524 }
539528
540529 // if this machine instr is call, insert caller saving code
541530
542 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
531 if ((TM.getInstrInfo()).isCall( MInst->getOpCode()) )
543532 MRI.insertCallerSavingCode(MInst, *BBI, *this );
544533
545534 */
550539 // mcInfo.popAllTempValues(TM);
551540 // TODO ** : do later
552541
553 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
542 //for (MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
554543
555544
556545 // Now replace set the registers for operands in the machine instruction
557546 //
558 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
547 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
559548
560549 MachineOperand& Op = MInst->getOperand(OpNum);
561550
562 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
551 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
563552 Op.getOperandType() == MachineOperand::MO_CCRegister) {
564553
565554 const Value *const Val = Op.getVRegValue();
566555
567556 // delete this condition checking later (must assert if Val is null)
568 if( !Val) {
557 if (!Val) {
569558 if (DEBUG_RA)
570559 cerr << "Warning: NULL Value found for operand\n";
571560 continue;
574563
575564 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
576565
577 if ( !LR ) {
566 if (!LR ) {
578567
579568 // nothing to worry if it's a const or a label
580569
585574 }
586575
587576 // if register is not allocated, mark register as invalid
588 if( Op.getAllocatedRegNum() == -1)
577 if (Op.getAllocatedRegNum() == -1)
589578 Op.setRegForValue( MRI.getInvalidRegNum());
590579
591580
594583
595584 unsigned RCID = (LR->getRegClass())->getID();
596585
597 if( LR->hasColor() ) {
586 if (LR->hasColor() ) {
598587 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
599588 }
600589 else {
603592 // for spilled opeands in this machine instruction
604593
605594 //assert(0 && "LR must be spilled");
606 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
595 insertCode4SpilledLR(LR, MInst, BBI, OpNum );
607596
608597 }
609598 }
619608 // If there are instructions to be added, *before* this machine
620609 // instruction, add them now.
621610 //
622 if(AddedInstrMap.count(MInst)) {
611 if (AddedInstrMap.count(MInst)) {
623612 PrependInstructions(AddedInstrMap[MInst].InstrnsBefore, MIVec, MII,"");
624613 }
625614
637626 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
638627 move2DelayedInstr(MInst, *(MII+delay) );
639628
640 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
629 if (DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
641630 }
642631
643632 else {
697686 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(),
698687 AdIMid.begin(), AdIMid.end());
699688
700 if(MIBef)
689 if (MIBef)
701690 AI.InstrnsBefore.push_back(MIBef);
702691
703 if(MIAft)
692 if (MIAft)
704693 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft);
705694
706695 } else { // if this is a Def
721710
722711 } // if !DEF
723712
724 cerr << "\nFor Inst " << *MInst;
725 cerr << " - SPILLED LR: "; printSet(*LR);
726 cerr << "\n - Added Instructions:";
727 if (MIBef) cerr << *MIBef;
728 for (vector::const_iterator II=AdIMid.begin();
729 II != AdIMid.end(); ++II)
730 cerr << **II;
731 if (MIAft) cerr << *MIAft;
713 if (DEBUG_RA) {
714 cerr << "\nFor Inst " << *MInst;
715 cerr << " - SPILLED LR: "; printSet(*LR);
716 cerr << "\n - Added Instructions:";
717 if (MIBef) cerr << *MIBef;
718 for (vector::const_iterator II=AdIMid.begin();
719 II != AdIMid.end(); ++II)
720 cerr << **II;
721 if (MIAft) cerr << *MIAft;
722 }
732723
733724 Op.setRegForValue(TmpRegU); // set the opearnd
734725 }
754745 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
755746
756747
757 if( RegU != -1) {
748 if (RegU != -1) {
758749 // we found an unused register, so we can simply use it
759750 MIBef = MIAft = NULL;
760751 }
798789
799790 std::vector &IsColorUsedArr = RC->getIsColorUsedArr();
800791
801 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
792 for (unsigned i=0; i < NumAvailRegs; i++) // Reset array
802793 IsColorUsedArr[i] = false;
803794
804795 ValueSet::const_iterator LIt = LVSetBef->begin();
805796
806797 // for each live var in live variable set after machine inst
807 for( ; LIt != LVSetBef->end(); ++LIt) {
798 for ( ; LIt != LVSetBef->end(); ++LIt) {
808799
809800 // get the live range corresponding to live var
810801 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
811802
812803 // LR can be null if it is a const since a const
813804 // doesn't have a dominating def - see Assumptions above
814 if( LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor() )
805 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor() )
815806 IsColorUsedArr[ LRofLV->getColor() ] = true;
816807 }
817808
821812
822813 setRelRegsUsedByThisInst(RC, MInst);
823814
824 for(unsigned c=0; c < NumAvailRegs; c++) // find first unused color
815 for (unsigned c=0; c < NumAvailRegs; c++) // find first unused color
825816 if (!IsColorUsedArr[c])
826817 return MRI.getUnifiedRegNum(RC->getID(), c);
827818
840831 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
841832
842833
843 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
834 for (unsigned i=0; i < NumAvailRegs ; i++) // Reset array
844835 IsColorUsedArr[i] = false;
845836
846837 setRelRegsUsedByThisInst(RC, MInst);
847838
848 for(unsigned c=0; c < RC->getNumOfAvailRegs(); c++)// find first unused color
839 for (unsigned c=0; c < RC->getNumOfAvailRegs(); c++)// find first unused color
849840 if (!IsColorUsedArr[c])
850841 return MRI.getUnifiedRegNum(RC->getID(), c);
851842
864855
865856 vector &IsColorUsedArr = RC->getIsColorUsedArr();
866857
867 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
858 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
868859
869860 const MachineOperand& Op = MInst->getOperand(OpNum);
870861
871 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
862 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
872863 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
873864
874865 const Value *const Val = Op.getVRegValue();
875866
876 if( Val )
877 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
867 if (Val )
868 if (MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
878869 int Reg;
879 if( (Reg=Op.getAllocatedRegNum()) != -1) {
870 if ((Reg=Op.getAllocatedRegNum()) != -1) {
880871 IsColorUsedArr[Reg] = true;
881872 }
882873 else {
884875 // a register but it has a LR and that received a color
885876
886877 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
887 if( LROfVal)
888 if( LROfVal->hasColor() )
878 if (LROfVal)
879 if (LROfVal->hasColor() )
889880 IsColorUsedArr[LROfVal->getColor()] = true;
890881 }
891882
899890
900891 // If there are implicit references, mark them as well
901892
902 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
893 for (unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
903894
904895 LiveRange *const LRofImpRef =
905896 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
906897
907 if(LRofImpRef && LRofImpRef->hasColor())
898 if (LRofImpRef && LRofImpRef->hasColor())
908899 IsColorUsedArr[LRofImpRef->getColor()] = true;
909900 }
910901 }
956947
957948 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
958949 BBI != BBE; ++BBI) {
959 cerr << "\n"; printLabel(*BBI); cerr << ": ";
950 cerr << "\n"; printLabel(BBI); cerr << ": ";
960951
961952 // get the iterator for machine instructions
962 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
953 MachineCodeForBasicBlock& MIVec = BBI->getMachineInstrVec();
963954 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
964955
965956 // iterate over all the machine instructions in BB
966 for( ; MII != MIVec.end(); ++MII) {
957 for ( ; MII != MIVec.end(); ++MII) {
967958 MachineInstr *const MInst = *MII;
968959
969960 cerr << "\n\t";
970961 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
971962
972 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
963 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
973964 MachineOperand& Op = MInst->getOperand(OpNum);
974965
975 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
966 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
976967 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
977968 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
978969
979970 const Value *const Val = Op.getVRegValue () ;
980971 // ****this code is temporary till NULL Values are fixed
981 if( ! Val ) {
972 if (! Val ) {
982973 cerr << "\t<*NULL*>";
983974 continue;
984975 }
985976
986977 // if a label or a constant
987 if(isa(Val)) {
978 if (isa(Val)) {
988979 cerr << "\t"; printLabel( Op.getVRegValue () );
989980 } else {
990981 // else it must be a register value
996987 else
997988 cerr << "(" << Val << ")";
998989
999 if( Op.opIsDef() )
990 if (Op.opIsDef() )
1000991 cerr << "*";
1001992
1002993 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1003 if( LROfVal )
1004 if( LROfVal->hasSpillOffset() )
994 if (LROfVal )
995 if (LROfVal->hasSpillOffset() )
1005996 cerr << "$";
1006997 }
1007998
1008999 }
1009 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1000 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
10101001 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
10111002 }
10121003
10171008
10181009
10191010 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1020 if( NumOfImpRefs > 0) {
1011 if (NumOfImpRefs > 0) {
10211012 cerr << "\tImplicit:";
10221013
1023 for(unsigned z=0; z < NumOfImpRefs; z++)
1014 for (unsigned z=0; z < NumOfImpRefs; z++)
10241015 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
10251016 }
10261017
10461037 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
10471038 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
10481039
1049 for( ; It != CallRetInstList.end(); ++It ) {
1040 for ( ; It != CallRetInstList.end(); ++It ) {
10501041
10511042 const MachineInstr *const CRMI = *It;
10521043 unsigned OpCode = CRMI->getOpCode();
10751066 //----------------------------------------------------------------------------
10761067 void PhyRegAlloc::colorIncomingArgs()
10771068 {
1078 const BasicBlock *const FirstBB = Meth->front();
1079 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1069 const BasicBlock &FirstBB = Meth->front();
1070 const MachineInstr *FirstMI = FirstBB.getMachineInstrVec().front();
10801071 assert(FirstMI && "No machine instruction in entry BB");
10811072
10821073 MRI.colorMethodArgs(Meth, LRI, &AddedInstrAtEntry);
11031094
11041095 void PhyRegAlloc::markUnusableSugColors()
11051096 {
1106 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1097 if (DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
11071098
11081099 // hash map iterator
11091100 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
11101101 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
11111102
1112 for(; HMI != HMIEnd ; ++HMI ) {
1103 for (; HMI != HMIEnd ; ++HMI ) {
11131104 if (HMI->first) {
11141105 LiveRange *L = HMI->second; // get the LiveRange
11151106 if (L) {
1116 if(L->hasSuggestedColor()) {
1107 if (L->hasSuggestedColor()) {
11171108 int RCID = L->getRegClass()->getID();
1118