Memory.h
00001 // This file is part of Eigen, a lightweight C++ template library
00002 // for linear algebra.
00003 //
00004 // Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
00005 // Copyright (C) 2008-2009 Benoit Jacob <jacob.benoit.1@gmail.com>
00006 // Copyright (C) 2009 Kenneth Riddile <kfriddile@yahoo.com>
00007 // Copyright (C) 2010 Hauke Heibel <hauke.heibel@gmail.com>
00008 // Copyright (C) 2010 Thomas Capricelli <orzel@freehackers.org>
00009 //
00010 // This Source Code Form is subject to the terms of the Mozilla
00011 // Public License v. 2.0. If a copy of the MPL was not distributed
00012 // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
00013 
00014 
00015 /*****************************************************************************
00016 *** Platform checks for aligned malloc functions                           ***
00017 *****************************************************************************/
00018 
00019 #ifndef EIGEN_MEMORY_H
00020 #define EIGEN_MEMORY_H
00021 
00022 // On 64-bit systems, glibc's malloc returns 16-byte-aligned pointers, see:
00023 //   http://www.gnu.org/s/libc/manual/html_node/Aligned-Memory-Blocks.html
00024 // This is true at least since glibc 2.8.
00025 // This leaves the question how to detect 64-bit. According to this document,
00026 //   http://gcc.fyxm.net/summit/2003/Porting%20to%2064%20bit.pdf
00027 // page 114, "[The] LP64 model [...] is used by all 64-bit UNIX ports" so it's indeed
00028 // quite safe, at least within the context of glibc, to equate 64-bit with LP64.
00029 #if defined(__GLIBC__) && ((__GLIBC__>=2 && __GLIBC_MINOR__ >= 8) || __GLIBC__>2) \
00030  && defined(__LP64__)
00031   #define EIGEN_GLIBC_MALLOC_ALREADY_ALIGNED 1
00032 #else
00033   #define EIGEN_GLIBC_MALLOC_ALREADY_ALIGNED 0
00034 #endif
00035 
00036 // FreeBSD 6 seems to have 16-byte aligned malloc
00037 //   See http://svn.freebsd.org/viewvc/base/stable/6/lib/libc/stdlib/malloc.c?view=markup
00038 // FreeBSD 7 seems to have 16-byte aligned malloc except on ARM and MIPS architectures
00039 //   See http://svn.freebsd.org/viewvc/base/stable/7/lib/libc/stdlib/malloc.c?view=markup
00040 #if defined(__FreeBSD__) && !defined(__arm__) && !defined(__mips__)
00041   #define EIGEN_FREEBSD_MALLOC_ALREADY_ALIGNED 1
00042 #else
00043   #define EIGEN_FREEBSD_MALLOC_ALREADY_ALIGNED 0
00044 #endif
00045 
00046 #if defined(__APPLE__) \
00047  || defined(_WIN64) \
00048  || EIGEN_GLIBC_MALLOC_ALREADY_ALIGNED \
00049  || EIGEN_FREEBSD_MALLOC_ALREADY_ALIGNED
00050   #define EIGEN_MALLOC_ALREADY_ALIGNED 1
00051 #else
00052   #define EIGEN_MALLOC_ALREADY_ALIGNED 0
00053 #endif
00054 
00055 #if ((defined __QNXNTO__) || (defined _GNU_SOURCE) || ((defined _XOPEN_SOURCE) && (_XOPEN_SOURCE >= 600))) \
00056  && (defined _POSIX_ADVISORY_INFO) && (_POSIX_ADVISORY_INFO > 0)
00057   #define EIGEN_HAS_POSIX_MEMALIGN 1
00058 #else
00059   #define EIGEN_HAS_POSIX_MEMALIGN 0
00060 #endif
00061 
00062 #ifdef EIGEN_VECTORIZE_SSE
00063   #define EIGEN_HAS_MM_MALLOC 1
00064 #else
00065   #define EIGEN_HAS_MM_MALLOC 0
00066 #endif
00067 
00068 namespace Eigen {
00069 
00070 namespace internal {
00071 
00072 inline void throw_std_bad_alloc()
00073 {
00074   #ifdef EIGEN_EXCEPTIONS
00075     throw std::bad_alloc();
00076   #else
00077     std::size_t huge = -1;
00078     new int[huge];
00079   #endif
00080 }
00081 
00082 /*****************************************************************************
00083 *** Implementation of handmade aligned functions                           ***
00084 *****************************************************************************/
00085 
00086 /* ----- Hand made implementations of aligned malloc/free and realloc ----- */
00087 
00091 inline void* handmade_aligned_malloc(std::size_t size)
00092 {
00093   void *original = std::malloc(size+16);
00094   if (original == 0) return 0;
00095   void *aligned = reinterpret_cast<void*>((reinterpret_cast<std::size_t>(original) & ~(std::size_t(15))) + 16);
00096   *(reinterpret_cast<void**>(aligned) - 1) = original;
00097   return aligned;
00098 }
00099 
00101 inline void handmade_aligned_free(void *ptr)
00102 {
00103   if (ptr) std::free(*(reinterpret_cast<void**>(ptr) - 1));
00104 }
00105 
00111 inline void* handmade_aligned_realloc(void* ptr, std::size_t size, std::size_t = 0)
00112 {
00113   if (ptr == 0) return handmade_aligned_malloc(size);
00114   void *original = *(reinterpret_cast<void**>(ptr) - 1);
00115   std::ptrdiff_t previous_offset = static_cast<char *>(ptr)-static_cast<char *>(original);
00116   original = std::realloc(original,size+16);
00117   if (original == 0) return 0;
00118   void *aligned = reinterpret_cast<void*>((reinterpret_cast<std::size_t>(original) & ~(std::size_t(15))) + 16);
00119   void *previous_aligned = static_cast<char *>(original)+previous_offset;
00120   if(aligned!=previous_aligned)
00121     std::memmove(aligned, previous_aligned, size);
00122   
00123   *(reinterpret_cast<void**>(aligned) - 1) = original;
00124   return aligned;
00125 }
00126 
00127 /*****************************************************************************
00128 *** Implementation of generic aligned realloc (when no realloc can be used)***
00129 *****************************************************************************/
00130 
00131 void* aligned_malloc(std::size_t size);
00132 void  aligned_free(void *ptr);
00133 
00139 inline void* generic_aligned_realloc(void* ptr, size_t size, size_t old_size)
00140 {
00141   if (ptr==0)
00142     return aligned_malloc(size);
00143 
00144   if (size==0)
00145   {
00146     aligned_free(ptr);
00147     return 0;
00148   }
00149 
00150   void* newptr = aligned_malloc(size);
00151   if (newptr == 0)
00152   {
00153     #ifdef EIGEN_HAS_ERRNO
00154     errno = ENOMEM; // according to the standard
00155     #endif
00156     return 0;
00157   }
00158 
00159   if (ptr != 0)
00160   {
00161     std::memcpy(newptr, ptr, (std::min)(size,old_size));
00162     aligned_free(ptr);
00163   }
00164 
00165   return newptr;
00166 }
00167 
00168 /*****************************************************************************
00169 *** Implementation of portable aligned versions of malloc/free/realloc     ***
00170 *****************************************************************************/
00171 
00172 #ifdef EIGEN_NO_MALLOC
00173 inline void check_that_malloc_is_allowed()
00174 {
00175   eigen_assert(false && "heap allocation is forbidden (EIGEN_NO_MALLOC is defined)");
00176 }
00177 #elif defined EIGEN_RUNTIME_NO_MALLOC
00178 inline bool is_malloc_allowed_impl(bool update, bool new_value = false)
00179 {
00180   static bool value = true;
00181   if (update == 1)
00182     value = new_value;
00183   return value;
00184 }
00185 inline bool is_malloc_allowed() { return is_malloc_allowed_impl(false); }
00186 inline bool set_is_malloc_allowed(bool new_value) { return is_malloc_allowed_impl(true, new_value); }
00187 inline void check_that_malloc_is_allowed()
00188 {
00189   eigen_assert(is_malloc_allowed() && "heap allocation is forbidden (EIGEN_RUNTIME_NO_MALLOC is defined and g_is_malloc_allowed is false)");
00190 }
00191 #else 
00192 inline void check_that_malloc_is_allowed()
00193 {}
00194 #endif
00195 
00199 inline void* aligned_malloc(size_t size)
00200 {
00201   check_that_malloc_is_allowed();
00202 
00203   void *result;
00204   #if !EIGEN_ALIGN
00205     result = std::malloc(size);
00206   #elif EIGEN_MALLOC_ALREADY_ALIGNED
00207     result = std::malloc(size);
00208   #elif EIGEN_HAS_POSIX_MEMALIGN
00209     if(posix_memalign(&result, 16, size)) result = 0;
00210   #elif EIGEN_HAS_MM_MALLOC
00211     result = _mm_malloc(size, 16);
00212 #elif defined(_MSC_VER) && (!defined(_WIN32_WCE))
00213     result = _aligned_malloc(size, 16);
00214   #else
00215     result = handmade_aligned_malloc(size);
00216   #endif
00217 
00218   if(!result && size)
00219     throw_std_bad_alloc();
00220 
00221   return result;
00222 }
00223 
00225 inline void aligned_free(void *ptr)
00226 {
00227   #if !EIGEN_ALIGN
00228     std::free(ptr);
00229   #elif EIGEN_MALLOC_ALREADY_ALIGNED
00230     std::free(ptr);
00231   #elif EIGEN_HAS_POSIX_MEMALIGN
00232     std::free(ptr);
00233   #elif EIGEN_HAS_MM_MALLOC
00234     _mm_free(ptr);
00235   #elif defined(_MSC_VER) && (!defined(_WIN32_WCE))
00236     _aligned_free(ptr);
00237   #else
00238     handmade_aligned_free(ptr);
00239   #endif
00240 }
00241 
00247 inline void* aligned_realloc(void *ptr, size_t new_size, size_t old_size)
00248 {
00249   EIGEN_UNUSED_VARIABLE(old_size);
00250 
00251   void *result;
00252 #if !EIGEN_ALIGN
00253   result = std::realloc(ptr,new_size);
00254 #elif EIGEN_MALLOC_ALREADY_ALIGNED
00255   result = std::realloc(ptr,new_size);
00256 #elif EIGEN_HAS_POSIX_MEMALIGN
00257   result = generic_aligned_realloc(ptr,new_size,old_size);
00258 #elif EIGEN_HAS_MM_MALLOC
00259   // The defined(_mm_free) is just here to verify that this MSVC version
00260   // implements _mm_malloc/_mm_free based on the corresponding _aligned_
00261   // functions. This may not always be the case and we just try to be safe.
00262   #if defined(_MSC_VER) && defined(_mm_free)
00263     result = _aligned_realloc(ptr,new_size,16);
00264   #else
00265     result = generic_aligned_realloc(ptr,new_size,old_size);
00266   #endif
00267 #elif defined(_MSC_VER)
00268   result = _aligned_realloc(ptr,new_size,16);
00269 #else
00270   result = handmade_aligned_realloc(ptr,new_size,old_size);
00271 #endif
00272 
00273   if (!result && new_size)
00274     throw_std_bad_alloc();
00275 
00276   return result;
00277 }
00278 
00279 /*****************************************************************************
00280 *** Implementation of conditionally aligned functions                      ***
00281 *****************************************************************************/
00282 
00286 template<bool Align> inline void* conditional_aligned_malloc(size_t size)
00287 {
00288   return aligned_malloc(size);
00289 }
00290 
00291 template<> inline void* conditional_aligned_malloc<false>(size_t size)
00292 {
00293   check_that_malloc_is_allowed();
00294 
00295   void *result = std::malloc(size);
00296   if(!result && size)
00297     throw_std_bad_alloc();
00298   return result;
00299 }
00300 
00302 template<bool Align> inline void conditional_aligned_free(void *ptr)
00303 {
00304   aligned_free(ptr);
00305 }
00306 
00307 template<> inline void conditional_aligned_free<false>(void *ptr)
00308 {
00309   std::free(ptr);
00310 }
00311 
00312 template<bool Align> inline void* conditional_aligned_realloc(void* ptr, size_t new_size, size_t old_size)
00313 {
00314   return aligned_realloc(ptr, new_size, old_size);
00315 }
00316 
00317 template<> inline void* conditional_aligned_realloc<false>(void* ptr, size_t new_size, size_t)
00318 {
00319   return std::realloc(ptr, new_size);
00320 }
00321 
00322 /*****************************************************************************
00323 *** Construction/destruction of array elements                             ***
00324 *****************************************************************************/
00325 
00329 template<typename T> inline T* construct_elements_of_array(T *ptr, size_t size)
00330 {
00331   for (size_t i=0; i < size; ++i) ::new (ptr + i) T;
00332   return ptr;
00333 }
00334 
00338 template<typename T> inline void destruct_elements_of_array(T *ptr, size_t size)
00339 {
00340   // always destruct an array starting from the end.
00341   if(ptr)
00342     while(size) ptr[--size].~T();
00343 }
00344 
00345 /*****************************************************************************
00346 *** Implementation of aligned new/delete-like functions                    ***
00347 *****************************************************************************/
00348 
00349 template<typename T>
00350 EIGEN_ALWAYS_INLINE void check_size_for_overflow(size_t size)
00351 {
00352   if(size > size_t(-1) / sizeof(T))
00353     throw_std_bad_alloc();
00354 }
00355 
00360 template<typename T> inline T* aligned_new(size_t size)
00361 {
00362   check_size_for_overflow<T>(size);
00363   T *result = reinterpret_cast<T*>(aligned_malloc(sizeof(T)*size));
00364   return construct_elements_of_array(result, size);
00365 }
00366 
00367 template<typename T, bool Align> inline T* conditional_aligned_new(size_t size)
00368 {
00369   check_size_for_overflow<T>(size);
00370   T *result = reinterpret_cast<T*>(conditional_aligned_malloc<Align>(sizeof(T)*size));
00371   return construct_elements_of_array(result, size);
00372 }
00373 
00377 template<typename T> inline void aligned_delete(T *ptr, size_t size)
00378 {
00379   destruct_elements_of_array<T>(ptr, size);
00380   aligned_free(ptr);
00381 }
00382 
00386 template<typename T, bool Align> inline void conditional_aligned_delete(T *ptr, size_t size)
00387 {
00388   destruct_elements_of_array<T>(ptr, size);
00389   conditional_aligned_free<Align>(ptr);
00390 }
00391 
00392 template<typename T, bool Align> inline T* conditional_aligned_realloc_new(T* pts, size_t new_size, size_t old_size)
00393 {
00394   check_size_for_overflow<T>(new_size);
00395   check_size_for_overflow<T>(old_size);
00396   if(new_size < old_size)
00397     destruct_elements_of_array(pts+new_size, old_size-new_size);
00398   T *result = reinterpret_cast<T*>(conditional_aligned_realloc<Align>(reinterpret_cast<void*>(pts), sizeof(T)*new_size, sizeof(T)*old_size));
00399   if(new_size > old_size)
00400     construct_elements_of_array(result+old_size, new_size-old_size);
00401   return result;
00402 }
00403 
00404 
00405 template<typename T, bool Align> inline T* conditional_aligned_new_auto(size_t size)
00406 {
00407   check_size_for_overflow<T>(size);
00408   T *result = reinterpret_cast<T*>(conditional_aligned_malloc<Align>(sizeof(T)*size));
00409   if(NumTraits<T>::RequireInitialization)
00410     construct_elements_of_array(result, size);
00411   return result;
00412 }
00413 
00414 template<typename T, bool Align> inline T* conditional_aligned_realloc_new_auto(T* pts, size_t new_size, size_t old_size)
00415 {
00416   check_size_for_overflow<T>(new_size);
00417   check_size_for_overflow<T>(old_size);
00418   if(NumTraits<T>::RequireInitialization && (new_size < old_size))
00419     destruct_elements_of_array(pts+new_size, old_size-new_size);
00420   T *result = reinterpret_cast<T*>(conditional_aligned_realloc<Align>(reinterpret_cast<void*>(pts), sizeof(T)*new_size, sizeof(T)*old_size));
00421   if(NumTraits<T>::RequireInitialization && (new_size > old_size))
00422     construct_elements_of_array(result+old_size, new_size-old_size);
00423   return result;
00424 }
00425 
00426 template<typename T, bool Align> inline void conditional_aligned_delete_auto(T *ptr, size_t size)
00427 {
00428   if(NumTraits<T>::RequireInitialization)
00429     destruct_elements_of_array<T>(ptr, size);
00430   conditional_aligned_free<Align>(ptr);
00431 }
00432 
00433 /****************************************************************************/
00434 
00451 template<typename Scalar, typename Index>
00452 static inline Index first_aligned(const Scalar* array, Index size)
00453 {
00454   typedef typename packet_traits<Scalar>::type Packet;
00455   enum { PacketSize = packet_traits<Scalar>::size,
00456          PacketAlignedMask = PacketSize-1
00457   };
00458 
00459   if(PacketSize==1)
00460   {
00461     // Either there is no vectorization, or a packet consists of exactly 1 scalar so that all elements
00462     // of the array have the same alignment.
00463     return 0;
00464   }
00465   else if(size_t(array) & (sizeof(Scalar)-1))
00466   {
00467     // There is vectorization for this scalar type, but the array is not aligned to the size of a single scalar.
00468     // Consequently, no element of the array is well aligned.
00469     return size;
00470   }
00471   else
00472   {
00473     return std::min<Index>( (PacketSize - (Index((size_t(array)/sizeof(Scalar))) & PacketAlignedMask))
00474                            & PacketAlignedMask, size);
00475   }
00476 }
00477 
00478 
00479 // std::copy is much slower than memcpy, so let's introduce a smart_copy which
00480 // use memcpy on trivial types, i.e., on types that does not require an initialization ctor.
00481 template<typename T, bool UseMemcpy> struct smart_copy_helper;
00482 
00483 template<typename T> void smart_copy(const T* start, const T* end, T* target)
00484 {
00485   smart_copy_helper<T,!NumTraits<T>::RequireInitialization>::run(start, end, target);
00486 }
00487 
00488 template<typename T> struct smart_copy_helper<T,true> {
00489   static inline void run(const T* start, const T* end, T* target)
00490   { memcpy(target, start, std::ptrdiff_t(end)-std::ptrdiff_t(start)); }
00491 };
00492 
00493 template<typename T> struct smart_copy_helper<T,false> {
00494   static inline void run(const T* start, const T* end, T* target)
00495   { std::copy(start, end, target); }
00496 };
00497 
00498 
00499 /*****************************************************************************
00500 *** Implementation of runtime stack allocation (falling back to malloc)    ***
00501 *****************************************************************************/
00502 
00503 // you can overwrite Eigen's default behavior regarding alloca by defining EIGEN_ALLOCA
00504 // to the appropriate stack allocation function
00505 #ifndef EIGEN_ALLOCA
00506   #if (defined __linux__)
00507     #define EIGEN_ALLOCA alloca
00508   #elif defined(_MSC_VER)
00509     #define EIGEN_ALLOCA _alloca
00510   #endif
00511 #endif
00512 
00513 // This helper class construct the allocated memory, and takes care of destructing and freeing the handled data
00514 // at destruction time. In practice this helper class is mainly useful to avoid memory leak in case of exceptions.
00515 template<typename T> class aligned_stack_memory_handler
00516 {
00517   public:
00518     /* Creates a stack_memory_handler responsible for the buffer \a ptr of size \a size.
00519      * Note that \a ptr can be 0 regardless of the other parameters.
00520      * This constructor takes care of constructing/initializing the elements of the buffer if required by the scalar type T (see NumTraits<T>::RequireInitialization).
00521      * In this case, the buffer elements will also be destructed when this handler will be destructed.
00522      * Finally, if \a dealloc is true, then the pointer \a ptr is freed.
00523      **/
00524     aligned_stack_memory_handler(T* ptr, size_t size, bool dealloc)
00525       : m_ptr(ptr), m_size(size), m_deallocate(dealloc)
00526     {
00527       if(NumTraits<T>::RequireInitialization && m_ptr)
00528         Eigen::internal::construct_elements_of_array(m_ptr, size);
00529     }
00530     ~aligned_stack_memory_handler()
00531     {
00532       if(NumTraits<T>::RequireInitialization && m_ptr)
00533         Eigen::internal::destruct_elements_of_array<T>(m_ptr, m_size);
00534       if(m_deallocate)
00535         Eigen::internal::aligned_free(m_ptr);
00536     }
00537   protected:
00538     T* m_ptr;
00539     size_t m_size;
00540     bool m_deallocate;
00541 };
00542 
00543 } // end namespace internal
00544 
00560 #ifdef EIGEN_ALLOCA
00561 
00562   #ifdef __arm__
00563     #define EIGEN_ALIGNED_ALLOCA(SIZE) reinterpret_cast<void*>((reinterpret_cast<size_t>(EIGEN_ALLOCA(SIZE+16)) & ~(size_t(15))) + 16)
00564   #else
00565     #define EIGEN_ALIGNED_ALLOCA EIGEN_ALLOCA
00566   #endif
00567 
00568   #define ei_declare_aligned_stack_constructed_variable(TYPE,NAME,SIZE,BUFFER) \
00569     Eigen::internal::check_size_for_overflow<TYPE>(SIZE); \
00570     TYPE* NAME = (BUFFER)!=0 ? (BUFFER) \
00571                : reinterpret_cast<TYPE*>( \
00572                       (sizeof(TYPE)*SIZE<=EIGEN_STACK_ALLOCATION_LIMIT) ? EIGEN_ALIGNED_ALLOCA(sizeof(TYPE)*SIZE) \
00573                     : Eigen::internal::aligned_malloc(sizeof(TYPE)*SIZE) );  \
00574     Eigen::internal::aligned_stack_memory_handler<TYPE> EIGEN_CAT(NAME,_stack_memory_destructor)((BUFFER)==0 ? NAME : 0,SIZE,sizeof(TYPE)*SIZE>EIGEN_STACK_ALLOCATION_LIMIT)
00575 
00576 #else
00577 
00578   #define ei_declare_aligned_stack_constructed_variable(TYPE,NAME,SIZE,BUFFER) \
00579     Eigen::internal::check_size_for_overflow<TYPE>(SIZE); \
00580     TYPE* NAME = (BUFFER)!=0 ? BUFFER : reinterpret_cast<TYPE*>(Eigen::internal::aligned_malloc(sizeof(TYPE)*SIZE));    \
00581     Eigen::internal::aligned_stack_memory_handler<TYPE> EIGEN_CAT(NAME,_stack_memory_destructor)((BUFFER)==0 ? NAME : 0,SIZE,true)
00582     
00583 #endif
00584 
00585 
00586 /*****************************************************************************
00587 *** Implementation of EIGEN_MAKE_ALIGNED_OPERATOR_NEW [_IF]                ***
00588 *****************************************************************************/
00589 
00590 #if EIGEN_ALIGN
00591   #ifdef EIGEN_EXCEPTIONS
00592     #define EIGEN_MAKE_ALIGNED_OPERATOR_NEW_NOTHROW(NeedsToAlign) \
00593       void* operator new(size_t size, const std::nothrow_t&) throw() { \
00594         try { return Eigen::internal::conditional_aligned_malloc<NeedsToAlign>(size); } \
00595         catch (...) { return 0; } \
00596         return 0; \
00597       }
00598   #else
00599     #define EIGEN_MAKE_ALIGNED_OPERATOR_NEW_NOTHROW(NeedsToAlign) \
00600       void* operator new(size_t size, const std::nothrow_t&) throw() { \
00601         return Eigen::internal::conditional_aligned_malloc<NeedsToAlign>(size); \
00602       }
00603   #endif
00604 
00605   #define EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(NeedsToAlign) \
00606       void *operator new(size_t size) { \
00607         return Eigen::internal::conditional_aligned_malloc<NeedsToAlign>(size); \
00608       } \
00609       void *operator new[](size_t size) { \
00610         return Eigen::internal::conditional_aligned_malloc<NeedsToAlign>(size); \
00611       } \
00612       void operator delete(void * ptr) throw() { Eigen::internal::conditional_aligned_free<NeedsToAlign>(ptr); } \
00613       void operator delete[](void * ptr) throw() { Eigen::internal::conditional_aligned_free<NeedsToAlign>(ptr); } \
00614       /* in-place new and delete. since (at least afaik) there is no actual   */ \
00615       /* memory allocated we can safely let the default implementation handle */ \
00616       /* this particular case. */ \
00617       static void *operator new(size_t size, void *ptr) { return ::operator new(size,ptr); } \
00618       void operator delete(void * memory, void *ptr) throw() { return ::operator delete(memory,ptr); } \
00619       /* nothrow-new (returns zero instead of std::bad_alloc) */ \
00620       EIGEN_MAKE_ALIGNED_OPERATOR_NEW_NOTHROW(NeedsToAlign) \
00621       void operator delete(void *ptr, const std::nothrow_t&) throw() { \
00622         Eigen::internal::conditional_aligned_free<NeedsToAlign>(ptr); \
00623       } \
00624       typedef void eigen_aligned_operator_new_marker_type;
00625 #else
00626   #define EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(NeedsToAlign)
00627 #endif
00628 
00629 #define EIGEN_MAKE_ALIGNED_OPERATOR_NEW EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(true)
00630 #define EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(Scalar,Size) \
00631   EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(bool(((Size)!=Eigen::Dynamic) && ((sizeof(Scalar)*(Size))%16==0)))
00632 
00633 /****************************************************************************/
00634 
00651 template<class T>
00652 class aligned_allocator
00653 {
00654 public:
00655     typedef size_t    size_type;
00656     typedef std::ptrdiff_t difference_type;
00657     typedef T*        pointer;
00658     typedef const T*  const_pointer;
00659     typedef T&        reference;
00660     typedef const T&  const_reference;
00661     typedef T         value_type;
00662 
00663     template<class U>
00664     struct rebind
00665     {
00666         typedef aligned_allocator<U> other;
00667     };
00668 
00669     pointer address( reference value ) const
00670     {
00671         return &value;
00672     }
00673 
00674     const_pointer address( const_reference value ) const
00675     {
00676         return &value;
00677     }
00678 
00679     aligned_allocator()
00680     {
00681     }
00682 
00683     aligned_allocator( const aligned_allocator& )
00684     {
00685     }
00686 
00687     template<class U>
00688     aligned_allocator( const aligned_allocator<U>& )
00689     {
00690     }
00691 
00692     ~aligned_allocator()
00693     {
00694     }
00695 
00696     size_type max_size() const
00697     {
00698         return (std::numeric_limits<size_type>::max)();
00699     }
00700 
00701     pointer allocate( size_type num, const void* hint = 0 )
00702     {
00703         EIGEN_UNUSED_VARIABLE(hint);
00704         internal::check_size_for_overflow<T>(num);
00705         return static_cast<pointer>( internal::aligned_malloc( num * sizeof(T) ) );
00706     }
00707 
00708     void construct( pointer p, const T& value )
00709     {
00710         ::new( p ) T( value );
00711     }
00712 
00713     // Support for c++11
00714 #if (__cplusplus >= 201103L)
00715     template<typename... Args>
00716     void  construct(pointer p, Args&&... args)
00717     {
00718       ::new(p) T(std::forward<Args>(args)...);
00719     }
00720 #endif
00721 
00722     void destroy( pointer p )
00723     {
00724         p->~T();
00725     }
00726 
00727     void deallocate( pointer p, size_type /*num*/ )
00728     {
00729         internal::aligned_free( p );
00730     }
00731 
00732     bool operator!=(const aligned_allocator<T>& ) const
00733     { return false; }
00734 
00735     bool operator==(const aligned_allocator<T>& ) const
00736     { return true; }
00737 };
00738 
00739 //---------- Cache sizes ----------
00740 
00741 #if !defined(EIGEN_NO_CPUID)
00742 #  if defined(__GNUC__) && ( defined(__i386__) || defined(__x86_64__) )
00743 #    if defined(__PIC__) && defined(__i386__)
00744        // Case for x86 with PIC
00745 #      define EIGEN_CPUID(abcd,func,id) \
00746          __asm__ __volatile__ ("xchgl %%ebx, %%esi;cpuid; xchgl %%ebx,%%esi": "=a" (abcd[0]), "=S" (abcd[1]), "=c" (abcd[2]), "=d" (abcd[3]) : "a" (func), "c" (id));
00747 #    else
00748        // Case for x86_64 or x86 w/o PIC
00749 #      define EIGEN_CPUID(abcd,func,id) \
00750          __asm__ __volatile__ ("cpuid": "=a" (abcd[0]), "=b" (abcd[1]), "=c" (abcd[2]), "=d" (abcd[3]) : "a" (func), "c" (id) );
00751 #    endif
00752 #  elif defined(_MSC_VER)
00753 #    if (_MSC_VER > 1500) && ( defined(_M_IX86) || defined(_M_X64) )
00754 #      define EIGEN_CPUID(abcd,func,id) __cpuidex((int*)abcd,func,id)
00755 #    endif
00756 #  endif
00757 #endif
00758 
00759 namespace internal {
00760 
00761 #ifdef EIGEN_CPUID
00762 
00763 inline bool cpuid_is_vendor(int abcd[4], const char* vendor)
00764 {
00765   return abcd[1]==(reinterpret_cast<const int*>(vendor))[0] && abcd[3]==(reinterpret_cast<const int*>(vendor))[1] && abcd[2]==(reinterpret_cast<const int*>(vendor))[2];
00766 }
00767 
00768 inline void queryCacheSizes_intel_direct(int& l1, int& l2, int& l3)
00769 {
00770   int abcd[4];
00771   l1 = l2 = l3 = 0;
00772   int cache_id = 0;
00773   int cache_type = 0;
00774   do {
00775     abcd[0] = abcd[1] = abcd[2] = abcd[3] = 0;
00776     EIGEN_CPUID(abcd,0x4,cache_id);
00777     cache_type  = (abcd[0] & 0x0F) >> 0;
00778     if(cache_type==1||cache_type==3) // data or unified cache
00779     {
00780       int cache_level = (abcd[0] & 0xE0) >> 5;  // A[7:5]
00781       int ways        = (abcd[1] & 0xFFC00000) >> 22; // B[31:22]
00782       int partitions  = (abcd[1] & 0x003FF000) >> 12; // B[21:12]
00783       int line_size   = (abcd[1] & 0x00000FFF) >>  0; // B[11:0]
00784       int sets        = (abcd[2]);                    // C[31:0]
00785 
00786       int cache_size = (ways+1) * (partitions+1) * (line_size+1) * (sets+1);
00787 
00788       switch(cache_level)
00789       {
00790         case 1: l1 = cache_size; break;
00791         case 2: l2 = cache_size; break;
00792         case 3: l3 = cache_size; break;
00793         default: break;
00794       }
00795     }
00796     cache_id++;
00797   } while(cache_type>0 && cache_id<16);
00798 }
00799 
00800 inline void queryCacheSizes_intel_codes(int& l1, int& l2, int& l3)
00801 {
00802   int abcd[4];
00803   abcd[0] = abcd[1] = abcd[2] = abcd[3] = 0;
00804   l1 = l2 = l3 = 0;
00805   EIGEN_CPUID(abcd,0x00000002,0);
00806   unsigned char * bytes = reinterpret_cast<unsigned char *>(abcd)+2;
00807   bool check_for_p2_core2 = false;
00808   for(int i=0; i<14; ++i)
00809   {
00810     switch(bytes[i])
00811     {
00812       case 0x0A: l1 = 8; break;   // 0Ah   data L1 cache, 8 KB, 2 ways, 32 byte lines
00813       case 0x0C: l1 = 16; break;  // 0Ch   data L1 cache, 16 KB, 4 ways, 32 byte lines
00814       case 0x0E: l1 = 24; break;  // 0Eh   data L1 cache, 24 KB, 6 ways, 64 byte lines
00815       case 0x10: l1 = 16; break;  // 10h   data L1 cache, 16 KB, 4 ways, 32 byte lines (IA-64)
00816       case 0x15: l1 = 16; break;  // 15h   code L1 cache, 16 KB, 4 ways, 32 byte lines (IA-64)
00817       case 0x2C: l1 = 32; break;  // 2Ch   data L1 cache, 32 KB, 8 ways, 64 byte lines
00818       case 0x30: l1 = 32; break;  // 30h   code L1 cache, 32 KB, 8 ways, 64 byte lines
00819       case 0x60: l1 = 16; break;  // 60h   data L1 cache, 16 KB, 8 ways, 64 byte lines, sectored
00820       case 0x66: l1 = 8; break;   // 66h   data L1 cache, 8 KB, 4 ways, 64 byte lines, sectored
00821       case 0x67: l1 = 16; break;  // 67h   data L1 cache, 16 KB, 4 ways, 64 byte lines, sectored
00822       case 0x68: l1 = 32; break;  // 68h   data L1 cache, 32 KB, 4 ways, 64 byte lines, sectored
00823       case 0x1A: l2 = 96; break;   // code and data L2 cache, 96 KB, 6 ways, 64 byte lines (IA-64)
00824       case 0x22: l3 = 512; break;   // code and data L3 cache, 512 KB, 4 ways (!), 64 byte lines, dual-sectored
00825       case 0x23: l3 = 1024; break;   // code and data L3 cache, 1024 KB, 8 ways, 64 byte lines, dual-sectored
00826       case 0x25: l3 = 2048; break;   // code and data L3 cache, 2048 KB, 8 ways, 64 byte lines, dual-sectored
00827       case 0x29: l3 = 4096; break;   // code and data L3 cache, 4096 KB, 8 ways, 64 byte lines, dual-sectored
00828       case 0x39: l2 = 128; break;   // code and data L2 cache, 128 KB, 4 ways, 64 byte lines, sectored
00829       case 0x3A: l2 = 192; break;   // code and data L2 cache, 192 KB, 6 ways, 64 byte lines, sectored
00830       case 0x3B: l2 = 128; break;   // code and data L2 cache, 128 KB, 2 ways, 64 byte lines, sectored
00831       case 0x3C: l2 = 256; break;   // code and data L2 cache, 256 KB, 4 ways, 64 byte lines, sectored
00832       case 0x3D: l2 = 384; break;   // code and data L2 cache, 384 KB, 6 ways, 64 byte lines, sectored
00833       case 0x3E: l2 = 512; break;   // code and data L2 cache, 512 KB, 4 ways, 64 byte lines, sectored
00834       case 0x40: l2 = 0; break;   // no integrated L2 cache (P6 core) or L3 cache (P4 core)
00835       case 0x41: l2 = 128; break;   // code and data L2 cache, 128 KB, 4 ways, 32 byte lines
00836       case 0x42: l2 = 256; break;   // code and data L2 cache, 256 KB, 4 ways, 32 byte lines
00837       case 0x43: l2 = 512; break;   // code and data L2 cache, 512 KB, 4 ways, 32 byte lines
00838       case 0x44: l2 = 1024; break;   // code and data L2 cache, 1024 KB, 4 ways, 32 byte lines
00839       case 0x45: l2 = 2048; break;   // code and data L2 cache, 2048 KB, 4 ways, 32 byte lines
00840       case 0x46: l3 = 4096; break;   // code and data L3 cache, 4096 KB, 4 ways, 64 byte lines
00841       case 0x47: l3 = 8192; break;   // code and data L3 cache, 8192 KB, 8 ways, 64 byte lines
00842       case 0x48: l2 = 3072; break;   // code and data L2 cache, 3072 KB, 12 ways, 64 byte lines
00843       case 0x49: if(l2!=0) l3 = 4096; else {check_for_p2_core2=true; l3 = l2 = 4096;} break;// code and data L3 cache, 4096 KB, 16 ways, 64 byte lines (P4) or L2 for core2
00844       case 0x4A: l3 = 6144; break;   // code and data L3 cache, 6144 KB, 12 ways, 64 byte lines
00845       case 0x4B: l3 = 8192; break;   // code and data L3 cache, 8192 KB, 16 ways, 64 byte lines
00846       case 0x4C: l3 = 12288; break;   // code and data L3 cache, 12288 KB, 12 ways, 64 byte lines
00847       case 0x4D: l3 = 16384; break;   // code and data L3 cache, 16384 KB, 16 ways, 64 byte lines
00848       case 0x4E: l2 = 6144; break;   // code and data L2 cache, 6144 KB, 24 ways, 64 byte lines
00849       case 0x78: l2 = 1024; break;   // code and data L2 cache, 1024 KB, 4 ways, 64 byte lines
00850       case 0x79: l2 = 128; break;   // code and data L2 cache, 128 KB, 8 ways, 64 byte lines, dual-sectored
00851       case 0x7A: l2 = 256; break;   // code and data L2 cache, 256 KB, 8 ways, 64 byte lines, dual-sectored
00852       case 0x7B: l2 = 512; break;   // code and data L2 cache, 512 KB, 8 ways, 64 byte lines, dual-sectored
00853       case 0x7C: l2 = 1024; break;   // code and data L2 cache, 1024 KB, 8 ways, 64 byte lines, dual-sectored
00854       case 0x7D: l2 = 2048; break;   // code and data L2 cache, 2048 KB, 8 ways, 64 byte lines
00855       case 0x7E: l2 = 256; break;   // code and data L2 cache, 256 KB, 8 ways, 128 byte lines, sect. (IA-64)
00856       case 0x7F: l2 = 512; break;   // code and data L2 cache, 512 KB, 2 ways, 64 byte lines
00857       case 0x80: l2 = 512; break;   // code and data L2 cache, 512 KB, 8 ways, 64 byte lines
00858       case 0x81: l2 = 128; break;   // code and data L2 cache, 128 KB, 8 ways, 32 byte lines
00859       case 0x82: l2 = 256; break;   // code and data L2 cache, 256 KB, 8 ways, 32 byte lines
00860       case 0x83: l2 = 512; break;   // code and data L2 cache, 512 KB, 8 ways, 32 byte lines
00861       case 0x84: l2 = 1024; break;   // code and data L2 cache, 1024 KB, 8 ways, 32 byte lines
00862       case 0x85: l2 = 2048; break;   // code and data L2 cache, 2048 KB, 8 ways, 32 byte lines
00863       case 0x86: l2 = 512; break;   // code and data L2 cache, 512 KB, 4 ways, 64 byte lines
00864       case 0x87: l2 = 1024; break;   // code and data L2 cache, 1024 KB, 8 ways, 64 byte lines
00865       case 0x88: l3 = 2048; break;   // code and data L3 cache, 2048 KB, 4 ways, 64 byte lines (IA-64)
00866       case 0x89: l3 = 4096; break;   // code and data L3 cache, 4096 KB, 4 ways, 64 byte lines (IA-64)
00867       case 0x8A: l3 = 8192; break;   // code and data L3 cache, 8192 KB, 4 ways, 64 byte lines (IA-64)
00868       case 0x8D: l3 = 3072; break;   // code and data L3 cache, 3072 KB, 12 ways, 128 byte lines (IA-64)
00869 
00870       default: break;
00871     }
00872   }
00873   if(check_for_p2_core2 && l2 == l3)
00874     l3 = 0;
00875   l1 *= 1024;
00876   l2 *= 1024;
00877   l3 *= 1024;
00878 }
00879 
00880 inline void queryCacheSizes_intel(int& l1, int& l2, int& l3, int max_std_funcs)
00881 {
00882   if(max_std_funcs>=4)
00883     queryCacheSizes_intel_direct(l1,l2,l3);
00884   else
00885     queryCacheSizes_intel_codes(l1,l2,l3);
00886 }
00887 
00888 inline void queryCacheSizes_amd(int& l1, int& l2, int& l3)
00889 {
00890   int abcd[4];
00891   abcd[0] = abcd[1] = abcd[2] = abcd[3] = 0;
00892   EIGEN_CPUID(abcd,0x80000005,0);
00893   l1 = (abcd[2] >> 24) * 1024; // C[31:24] = L1 size in KB
00894   abcd[0] = abcd[1] = abcd[2] = abcd[3] = 0;
00895   EIGEN_CPUID(abcd,0x80000006,0);
00896   l2 = (abcd[2] >> 16) * 1024; // C[31;16] = l2 cache size in KB
00897   l3 = ((abcd[3] & 0xFFFC000) >> 18) * 512 * 1024; // D[31;18] = l3 cache size in 512KB
00898 }
00899 #endif
00900 
00903 inline void queryCacheSizes(int& l1, int& l2, int& l3)
00904 {
00905   #ifdef EIGEN_CPUID
00906   int abcd[4];
00907 
00908   // identify the CPU vendor
00909   EIGEN_CPUID(abcd,0x0,0);
00910   int max_std_funcs = abcd[1];
00911   if(cpuid_is_vendor(abcd,"GenuineIntel"))
00912     queryCacheSizes_intel(l1,l2,l3,max_std_funcs);
00913   else if(cpuid_is_vendor(abcd,"AuthenticAMD") || cpuid_is_vendor(abcd,"AMDisbetter!"))
00914     queryCacheSizes_amd(l1,l2,l3);
00915   else
00916     // by default let's use Intel's API
00917     queryCacheSizes_intel(l1,l2,l3,max_std_funcs);
00918 
00919   // here is the list of other vendors:
00920 //   ||cpuid_is_vendor(abcd,"VIA VIA VIA ")
00921 //   ||cpuid_is_vendor(abcd,"CyrixInstead")
00922 //   ||cpuid_is_vendor(abcd,"CentaurHauls")
00923 //   ||cpuid_is_vendor(abcd,"GenuineTMx86")
00924 //   ||cpuid_is_vendor(abcd,"TransmetaCPU")
00925 //   ||cpuid_is_vendor(abcd,"RiseRiseRise")
00926 //   ||cpuid_is_vendor(abcd,"Geode by NSC")
00927 //   ||cpuid_is_vendor(abcd,"SiS SiS SiS ")
00928 //   ||cpuid_is_vendor(abcd,"UMC UMC UMC ")
00929 //   ||cpuid_is_vendor(abcd,"NexGenDriven")
00930   #else
00931   l1 = l2 = l3 = -1;
00932   #endif
00933 }
00934 
00937 inline int queryL1CacheSize()
00938 {
00939   int l1(-1), l2, l3;
00940   queryCacheSizes(l1,l2,l3);
00941   return l1;
00942 }
00943 
00946 inline int queryTopLevelCacheSize()
00947 {
00948   int l1, l2(-1), l3(-1);
00949   queryCacheSizes(l1,l2,l3);
00950   return (std::max)(l2,l3);
00951 }
00952 
00953 } // end namespace internal
00954 
00955 } // end namespace Eigen
00956 
00957 #endif // EIGEN_MEMORY_H