source: src/Common/utility.h@ 351c519

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr persistent-indexer pthread-emulation qualifiedEnum
Last change on this file since 351c519 was fbecee5, checked in by Aaron Moss <a3moss@…>, 7 years ago

rational.cfa passes deferred resolution pass now

  • Property mode set to 100644
File size: 14.4 KB
RevLine 
[51587aa]1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
[60089f4]7// utility.h --
[51587aa]8//
9// Author : Richard C. Bilson
10// Created On : Mon May 18 07:44:20 2015
[9dc31c10]11// Last Modified By : Peter A. Buhr
[b6d7f44]12// Last Modified On : Sun May 6 22:24:16 2018
13// Update Count : 40
[51587aa]14//
[01aeade]15
[6b0b624]16#pragma once
[51b73452]17
[e491159]18#include <cctype>
[940bba3]19#include <algorithm>
[2e30d47]20#include <functional>
[51b73452]21#include <iostream>
22#include <iterator>
23#include <list>
[e491159]24#include <memory>
25#include <sstream>
26#include <string>
[55a68c3]27#include <type_traits>
[fbecee5]28#include <utility>
[51b73452]29
[294647b]30#include <cassert>
[be9288a]31
[50377a4]32#include "Common/Indenter.h"
33
[5cbacf1]34class Expression;
35
[51b73452]36template< typename T >
[01aeade]37static inline T * maybeClone( const T *orig ) {
38 if ( orig ) {
39 return orig->clone();
40 } else {
41 return 0;
42 } // if
[51b73452]43}
44
[a7741435]45template< typename T, typename U >
[e04ef3a]46struct maybeBuild_t {
47 static T * doit( const U *orig ) {
48 if ( orig ) {
49 return orig->build();
50 } else {
51 return 0;
52 } // if
53 }
54};
55
[51b73452]56template< typename T, typename U >
[01aeade]57static inline T * maybeBuild( const U *orig ) {
[e04ef3a]58 return maybeBuild_t<T,U>::doit(orig);
[51b73452]59}
60
[7ecbb7e]61template< typename T, typename U >
62static inline T * maybeMoveBuild( const U *orig ) {
63 T* ret = maybeBuild<T>(orig);
64 delete orig;
65 return ret;
66}
67
[51b73452]68template< typename Input_iterator >
[01aeade]69void printEnums( Input_iterator begin, Input_iterator end, const char * const *name_array, std::ostream &os ) {
70 for ( Input_iterator i = begin; i != end; ++i ) {
71 os << name_array[ *i ] << ' ';
72 } // for
[51b73452]73}
74
75template< typename Container >
[01aeade]76void deleteAll( Container &container ) {
77 for ( typename Container::iterator i = container.begin(); i != container.end(); ++i ) {
78 delete *i;
79 } // for
[51b73452]80}
81
82template< typename Container >
[50377a4]83void printAll( const Container &container, std::ostream &os, Indenter indent = {} ) {
[01aeade]84 for ( typename Container::const_iterator i = container.begin(); i != container.end(); ++i ) {
85 if ( *i ) {
[50377a4]86 os << indent;
87 (*i)->print( os, indent );
[60089f4]88 // need an endl after each element because it's not easy to know when each individual item should end
[01aeade]89 os << std::endl;
90 } // if
91 } // for
[51b73452]92}
93
94template< typename SrcContainer, typename DestContainer >
[01aeade]95void cloneAll( const SrcContainer &src, DestContainer &dest ) {
96 typename SrcContainer::const_iterator in = src.begin();
97 std::back_insert_iterator< DestContainer > out( dest );
98 while ( in != src.end() ) {
99 *out++ = (*in++)->clone();
100 } // while
[51b73452]101}
102
[54c9000]103template< typename SrcContainer, typename DestContainer, typename Predicate >
104void cloneAll_if( const SrcContainer &src, DestContainer &dest, Predicate pred ) {
105 std::back_insert_iterator< DestContainer > out( dest );
106 for ( auto x : src ) {
107 if ( pred(x) ) {
108 *out++ = x->clone();
109 }
110 } // while
111}
112
[51b73452]113template< typename Container >
[01aeade]114void assertAll( const Container &container ) {
115 int count = 0;
116 for ( typename Container::const_iterator i = container.begin(); i != container.end(); ++i ) {
117 if ( !(*i) ) {
118 std::cerr << count << " is null" << std::endl;
119 } // if
120 } // for
121}
122
[51b73452]123template < typename T >
[01aeade]124std::list<T> tail( std::list<T> l ) {
125 if ( ! l.empty() ) {
126 std::list<T> ret(++(l.begin()), l.end());
127 return ret;
128 } // if
[51b73452]129}
130
131template < typename T >
132std::list<T> flatten( std::list < std::list<T> > l) {
[01aeade]133 typedef std::list <T> Ts;
[51b73452]134
[01aeade]135 Ts ret;
[51b73452]136
[a08ba92]137 switch ( l.size() ) {
[01aeade]138 case 0:
139 return ret;
140 case 1:
141 return l.front();
142 default:
143 ret = flatten(tail(l));
144 ret.insert(ret.begin(), l.front().begin(), l.front().end());
145 return ret;
146 } // switch
[51b73452]147}
148
[60089f4]149template < typename T >
[2298f728]150void toString_single( std::ostream & os, const T & value ) {
[79970ed]151 os << value;
152}
153
154template < typename T, typename... Params >
[2298f728]155void toString_single( std::ostream & os, const T & value, const Params & ... params ) {
[79970ed]156 os << value;
157 toString_single( os, params ... );
158}
159
160template < typename ... Params >
[2298f728]161std::string toString( const Params & ... params ) {
[5f2f2d7]162 std::ostringstream os;
[79970ed]163 toString_single( os, params... );
[5f2f2d7]164 return os.str();
[51b73452]165}
166
[babeeda]167#define toCString( ... ) toString( __VA_ARGS__ ).c_str()
168
[3c13c03]169// replace element of list with all elements of another list
[51b73452]170template< typename T >
171void replace( std::list< T > &org, typename std::list< T >::iterator pos, std::list< T > &with ) {
[01aeade]172 typename std::list< T >::iterator next = pos; advance( next, 1 );
[51b73452]173
[01aeade]174 //if ( next != org.end() ) {
[a08ba92]175 org.erase( pos );
176 org.splice( next, with );
177 //}
[51b73452]178
[01aeade]179 return;
[51b73452]180}
181
[3c13c03]182// replace range of a list with a single element
183template< typename T >
184void replace( std::list< T > &org, typename std::list< T >::iterator begin, typename std::list< T >::iterator end, const T & with ) {
185 org.insert( begin, with );
186 org.erase( begin, end );
187}
188
[940bba3]189template< typename... Args >
190auto filter(Args&&... args) -> decltype(std::copy_if(std::forward<Args>(args)...)) {
191 return std::copy_if(std::forward<Args>(args)...);
[51b73452]192}
193
[2bf9c37]194template <typename E, typename UnaryPredicate, template< typename, typename...> class Container, typename... Args >
195void filter( Container< E *, Args... > & container, UnaryPredicate pred, bool doDelete ) {
196 auto i = begin( container );
197 while ( i != end( container ) ) {
198 auto it = next( i );
199 if ( pred( *i ) ) {
200 if ( doDelete ) {
201 delete *i;
202 } // if
203 container.erase( i );
204 } // if
205 i = it;
206 } // while
207}
208
[940bba3]209template< typename... Args >
210auto zip(Args&&... args) -> decltype(zipWith(std::forward<Args>(args)..., std::make_pair)) {
211 return zipWith(std::forward<Args>(args)..., std::make_pair);
[51b73452]212}
213
214template< class InputIterator1, class InputIterator2, class OutputIterator, class BinFunction >
215void zipWith( InputIterator1 b1, InputIterator1 e1, InputIterator2 b2, InputIterator2 e2, OutputIterator out, BinFunction func ) {
[01aeade]216 while ( b1 != e1 && b2 != e2 )
217 *out++ = func(*b1++, *b2++);
[51b73452]218}
219
[d939274]220// it's nice to actually be able to increment iterators by an arbitrary amount
[940bba3]221template< class InputIt, class Distance >
222InputIt operator+( InputIt it, Distance n ) {
223 advance(it, n);
224 return it;
[d939274]225}
226
[79970ed]227template< typename T >
228void warn_single( const T & arg ) {
229 std::cerr << arg << std::endl;
230}
231
232template< typename T, typename... Params >
233void warn_single(const T & arg, const Params & ... params ) {
234 std::cerr << arg;
235 warn_single( params... );
236}
237
238template< typename... Params >
239void warn( const Params & ... params ) {
240 std::cerr << "Warning: ";
241 warn_single( params... );
242}
243
[bc3127d]244/// determines if `pref` is a prefix of `str`
245static inline bool isPrefix( const std::string & str, const std::string & pref ) {
246 if ( pref.size() > str.size() ) return false;
247 auto its = std::mismatch( pref.begin(), pref.end(), str.begin() );
248 return its.first == pref.end();
249}
250
[940bba3]251// -----------------------------------------------------------------------------
252// Ref Counted Singleton class
253// Objects that inherit from this class will have at most one reference to it
254// but if all references die, the object will be deleted.
255
[e491159]256template< typename ThisType >
257class RefCountSingleton {
258 public:
259 static std::shared_ptr<ThisType> get() {
260 if( global_instance.expired() ) {
261 std::shared_ptr<ThisType> new_instance = std::make_shared<ThisType>();
262 global_instance = new_instance;
263 return std::move(new_instance);
264 }
265 return global_instance.lock();
266 }
267 private:
268 static std::weak_ptr<ThisType> global_instance;
269};
270
[1f75e2d]271template< typename ThisType >
272std::weak_ptr<ThisType> RefCountSingleton<ThisType>::global_instance;
273
[940bba3]274// -----------------------------------------------------------------------------
[c8dfcd3]275// RAII object to regulate "save and restore" behaviour, e.g.
276// void Foo::bar() {
277// ValueGuard<int> guard(var); // var is a member of type Foo
278// var = ...;
279// } // var's original value is restored
280template< typename T >
281struct ValueGuard {
282 T old;
283 T& ref;
284
285 ValueGuard(T& inRef) : old(inRef), ref(inRef) {}
286 ~ValueGuard() { ref = old; }
287};
288
[134322e]289template< typename T >
290struct ValueGuardPtr {
291 T old;
292 T* ref;
293
294 ValueGuardPtr(T * inRef) : old( inRef ? *inRef : T() ), ref(inRef) {}
295 ~ValueGuardPtr() { if( ref ) *ref = old; }
296};
297
[234223f]298template< typename aT >
299struct FuncGuard {
300 aT m_after;
301
302 template< typename bT >
303 FuncGuard( bT before, aT after ) : m_after( after ) {
304 before();
305 }
306
307 ~FuncGuard() {
308 m_after();
309 }
310};
311
312template< typename bT, typename aT >
313FuncGuard<aT> makeFuncGuard( bT && before, aT && after ) {
314 return FuncGuard<aT>( std::forward<bT>(before), std::forward<aT>(after) );
315}
316
[134322e]317template< typename T >
318struct ValueGuardPtr< std::list< T > > {
319 std::list< T > old;
320 std::list< T >* ref;
321
322 ValueGuardPtr( std::list< T > * inRef) : old(), ref(inRef) {
323 if( ref ) { swap( *ref, old ); }
324 }
325 ~ValueGuardPtr() { if( ref ) { swap( *ref, old ); } }
326};
327
[940bba3]328// -----------------------------------------------------------------------------
329// Helper struct and function to support
330// for ( val : reverseIterate( container ) ) {}
331// syntax to have a for each that iterates backwards
332
[44f6341]333template< typename T >
[4a9ccc3]334struct reverse_iterate_t {
[44f6341]335 T& ref;
336
[4a9ccc3]337 reverse_iterate_t( T & ref ) : ref(ref) {}
[44f6341]338
339 typedef typename T::reverse_iterator iterator;
340 iterator begin() { return ref.rbegin(); }
341 iterator end() { return ref.rend(); }
342};
343
344template< typename T >
[4a9ccc3]345reverse_iterate_t< T > reverseIterate( T & ref ) {
346 return reverse_iterate_t< T >( ref );
[44f6341]347}
348
[3ad7978]349template< typename OutType, typename Range, typename Functor >
350OutType map_range( const Range& range, Functor&& functor ) {
351 OutType out;
352
353 std::transform(
354 begin( range ),
355 end( range ),
356 std::back_inserter( out ),
357 std::forward< Functor >( functor )
358 );
359
360 return out;
361}
362
[4a9ccc3]363// -----------------------------------------------------------------------------
364// Helper struct and function to support
365// for ( val : group_iterate( container1, container2, ... ) ) {}
366// syntax to have a for each that iterates multiple containers of the same length
[55a68c3]367// TODO: update to use variadic arguments
[4a9ccc3]368
369template< typename T1, typename T2 >
370struct group_iterate_t {
[50377a4]371private:
372 std::tuple<T1, T2> args;
373public:
[6d267ca]374 group_iterate_t( bool skipBoundsCheck, const T1 & v1, const T2 & v2 ) : args(v1, v2) {
[3c09d47]375 assertf(skipBoundsCheck || v1.size() == v2.size(), "group iteration requires containers of the same size: <%zd, %zd>.", v1.size(), v2.size());
[4a9ccc3]376 };
377
[50377a4]378 typedef std::tuple<decltype(*std::get<0>(args).begin()), decltype(*std::get<1>(args).begin())> value_type;
379 typedef decltype(std::get<0>(args).begin()) T1Iter;
380 typedef decltype(std::get<1>(args).begin()) T2Iter;
381
[4a9ccc3]382 struct iterator {
383 typedef std::tuple<T1Iter, T2Iter> IterTuple;
384 IterTuple it;
385 iterator( T1Iter i1, T2Iter i2 ) : it( i1, i2 ) {}
386 iterator operator++() {
387 return iterator( ++std::get<0>(it), ++std::get<1>(it) );
388 }
389 bool operator!=( const iterator &other ) const { return it != other.it; }
[55a68c3]390 value_type operator*() const { return std::tie( *std::get<0>(it), *std::get<1>(it) ); }
[4a9ccc3]391 };
[50377a4]392
[4a9ccc3]393 iterator begin() { return iterator( std::get<0>(args).begin(), std::get<1>(args).begin() ); }
394 iterator end() { return iterator( std::get<0>(args).end(), std::get<1>(args).end() ); }
395};
396
[6d267ca]397/// performs bounds check to ensure that all arguments are of the same length.
[4a9ccc3]398template< typename... Args >
[55a68c3]399group_iterate_t<Args...> group_iterate( Args &&... args ) {
[6d267ca]400 return group_iterate_t<Args...>(false, std::forward<Args>( args )...);
401}
402
403/// does not perform a bounds check - requires user to ensure that iteration terminates when appropriate.
404template< typename... Args >
405group_iterate_t<Args...> unsafe_group_iterate( Args &&... args ) {
406 return group_iterate_t<Args...>(true, std::forward<Args>( args )...);
[4a9ccc3]407}
[294647b]408
[108f3cdb]409// -----------------------------------------------------------------------------
410// Helper struct and function to support
411// for ( val : lazy_map( container1, f ) ) {}
412// syntax to have a for each that iterates a container, mapping each element by applying f
413template< typename T, typename Func >
414struct lambda_iterate_t {
[4639b0d]415 const T & ref;
416 std::function<Func> f;
[108f3cdb]417
418 struct iterator {
419 typedef decltype(begin(ref)) Iter;
420 Iter it;
[4639b0d]421 std::function<Func> f;
422 iterator( Iter it, std::function<Func> f ) : it(it), f(f) {}
[108f3cdb]423 iterator & operator++() {
424 ++it; return *this;
425 }
426 bool operator!=( const iterator &other ) const { return it != other.it; }
427 auto operator*() const -> decltype(f(*it)) { return f(*it); }
428 };
429
[4639b0d]430 lambda_iterate_t( const T & ref, std::function<Func> f ) : ref(ref), f(f) {}
[108f3cdb]431
432 auto begin() const -> decltype(iterator(std::begin(ref), f)) { return iterator(std::begin(ref), f); }
433 auto end() const -> decltype(iterator(std::end(ref), f)) { return iterator(std::end(ref), f); }
434};
435
436template< typename... Args >
[4639b0d]437lambda_iterate_t<Args...> lazy_map( const Args &... args ) {
438 return lambda_iterate_t<Args...>( args...);
[108f3cdb]439}
440
[9dc31c10]441// -----------------------------------------------------------------------------
[f14d956]442// O(1) polymorphic integer ilog2, using clz, which returns the number of leading 0-bits, starting at the most
[9dc31c10]443// significant bit (single instruction on x86)
444
445template<typename T>
[d28a03e]446inline
[b6d7f44]447#if defined(__GNUC__) && __GNUC__ > 4
[d28a03e]448constexpr
449#endif
450T ilog2(const T & t) {
451 if(std::is_integral<T>::value) {
[9dc31c10]452 const constexpr int r = sizeof(t) * __CHAR_BIT__ - 1;
[d28a03e]453 if( sizeof(T) == sizeof(unsigned int) ) return r - __builtin_clz ( t );
454 if( sizeof(T) == sizeof(unsigned long) ) return r - __builtin_clzl ( t );
455 if( sizeof(T) == sizeof(unsigned long long) ) return r - __builtin_clzll( t );
456 }
457 assert(false);
[9dc31c10]458 return -1;
[01b8ccf1]459} // ilog2
[108f3cdb]460
[5cbacf1]461// -----------------------------------------------------------------------------
462/// evaluates expr as a long long int. If second is false, expr could not be evaluated
463std::pair<long long int, bool> eval(Expression * expr);
[108f3cdb]464
[fbecee5]465// -----------------------------------------------------------------------------
466/// Reorders the input range in-place so that the minimal-value elements according to the
467/// comparator are in front;
468/// returns the iterator after the last minimal-value element.
469template<typename Iter, typename Compare>
470Iter sort_mins( Iter begin, Iter end, Compare& lt ) {
471 if ( begin == end ) return end;
472
473 Iter min_pos = begin;
474 for ( Iter i = begin + 1; i != end; ++i ) {
475 if ( lt( *i, *min_pos ) ) {
476 // new minimum cost; swap into first position
477 min_pos = begin;
478 std::iter_swap( min_pos, i );
479 } else if ( ! lt( *min_pos, *i ) ) {
480 // duplicate minimum cost; swap into next minimum position
481 ++min_pos;
482 std::iter_swap( min_pos, i );
483 }
484 }
485 return ++min_pos;
486}
487
488template<typename Iter, typename Compare>
489inline Iter sort_mins( Iter begin, Iter end, Compare&& lt ) {
490 return sort_mins( begin, end, lt );
491}
492
493/// sort_mins defaulted to use std::less
494template<typename Iter>
495inline Iter sort_mins( Iter begin, Iter end ) {
496 return sort_mins( begin, end, std::less<typename std::iterator_traits<Iter>::value_type>{} );
497}
498
[51587aa]499// Local Variables: //
500// tab-width: 4 //
501// mode: c++ //
502// compile-command: "make install" //
503// End: //
Note: See TracBrowser for help on using the repository browser.