1 /*
   2  * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #ifndef SHARE_VM_RUNTIME_ATOMIC_HPP
  26 #define SHARE_VM_RUNTIME_ATOMIC_HPP
  27 
  28 #include "memory/allocation.hpp"
  29 #include "metaprogramming/conditional.hpp"
  30 #include "metaprogramming/enableIf.hpp"
  31 #include "metaprogramming/isIntegral.hpp"
  32 #include "metaprogramming/isPointer.hpp"
  33 #include "metaprogramming/isSame.hpp"
  34 #include "metaprogramming/primitiveConversions.hpp"
  35 #include "metaprogramming/removeCV.hpp"
  36 #include "metaprogramming/removePointer.hpp"
  37 #include "utilities/align.hpp"
  38 #include "utilities/macros.hpp"
  39 
  40 enum cmpxchg_memory_order {
  41   memory_order_relaxed,
  42   // Use value which doesn't interfere with C++2011. We need to be more conservative.
  43   memory_order_conservative = 8
  44 };
  45 
  46 class Atomic : AllStatic {
  47  public:
  48   // Atomic operations on jlong types are not available on all 32-bit
  49   // platforms. If atomic ops on jlongs are defined here they must only
  50   // be used from code that verifies they are available at runtime and
  51   // can provide an alternative action if not - see supports_cx8() for
  52   // a means to test availability.
  53 
  54   // The memory operations that are mentioned with each of the atomic
  55   // function families come from src/share/vm/runtime/orderAccess.hpp,
  56   // e.g., <fence> is described in that file and is implemented by the
  57   // OrderAccess::fence() function. See that file for the gory details
  58   // on the Memory Access Ordering Model.
  59 
  60   // All of the atomic operations that imply a read-modify-write action
  61   // guarantee a two-way memory barrier across that operation. Historically
  62   // these semantics reflect the strength of atomic operations that are
  63   // provided on SPARC/X86. We assume that strength is necessary unless
  64   // we can prove that a weaker form is sufficiently safe.
  65 
  66   // Atomically store to a location
  67   // The type T must be either a pointer type convertible to or equal
  68   // to D, an integral/enum type equal to D, or a type equal to D that
  69   // is primitive convertible using PrimitiveConversions.
  70   template<typename T, typename D>
  71   inline static void store(T store_value, volatile D* dest);
  72 
  73   inline static void store_ptr(intptr_t store_value, volatile intptr_t* dest) {
  74     Atomic::store(store_value, dest);
  75   }
  76 
  77   inline static void store_ptr(void*    store_value, volatile void*     dest) {
  78     Atomic::store(store_value, reinterpret_cast<void* volatile*>(dest));
  79   }
  80 
  81   // Atomically load from a location
  82   // The type T must be either a pointer type, an integral/enum type,
  83   // or a type that is primitive convertible using PrimitiveConversions.
  84   template<typename T>
  85   inline static T load(const volatile T* dest);
  86 
  87   // Atomically add to a location. Returns updated value. add*() provide:
  88   // <fence> add-value-to-dest <membar StoreLoad|StoreStore>
  89 
  90   template<typename I, typename D>
  91   inline static D add(I add_value, D volatile* dest);
  92 
  93   inline static intptr_t add_ptr(intptr_t add_value, volatile intptr_t* dest) {
  94     return add(add_value, dest);
  95   }
  96 
  97   inline static void* add_ptr(intptr_t add_value, volatile void* dest) {
  98     return add(add_value, reinterpret_cast<char* volatile*>(dest));
  99   }
 100 
 101   // Atomically increment location. inc() provide:
 102   // <fence> increment-dest <membar StoreLoad|StoreStore>
 103   // The type D may be either a pointer type, or an integral
 104   // type. If it is a pointer type, then the increment is
 105   // scaled to the size of the type pointed to by the pointer.
 106   template<typename D>
 107   inline static void inc(D volatile* dest);
 108 
 109   // Atomically decrement a location. dec() provide:
 110   // <fence> decrement-dest <membar StoreLoad|StoreStore>
 111   // The type D may be either a pointer type, or an integral
 112   // type. If it is a pointer type, then the decrement is
 113   // scaled to the size of the type pointed to by the pointer.
 114   template<typename D>
 115   inline static void dec(D volatile* dest);
 116 
 117   // Performs atomic exchange of *dest with exchange_value. Returns old
 118   // prior value of *dest. xchg*() provide:
 119   // <fence> exchange-value-with-dest <membar StoreLoad|StoreStore>
 120   // The type T must be either a pointer type convertible to or equal
 121   // to D, an integral/enum type equal to D, or a type equal to D that
 122   // is primitive convertible using PrimitiveConversions.
 123   template<typename T, typename D>
 124   inline static D xchg(T exchange_value, volatile D* dest);
 125 
 126   inline static intptr_t xchg_ptr(intptr_t exchange_value, volatile intptr_t* dest) {
 127     return xchg(exchange_value, dest);
 128   }
 129 
 130   inline static void*    xchg_ptr(void*    exchange_value, volatile void*     dest) {
 131     return xchg(exchange_value, reinterpret_cast<void* volatile*>(dest));
 132   }
 133 
 134   // Performs atomic compare of *dest and compare_value, and exchanges
 135   // *dest with exchange_value if the comparison succeeded. Returns prior
 136   // value of *dest. cmpxchg*() provide:
 137   // <fence> compare-and-exchange <membar StoreLoad|StoreStore>
 138 
 139   template<typename T, typename D, typename U>
 140   inline static D cmpxchg(T exchange_value,
 141                           D volatile* dest,
 142                           U compare_value,
 143                           cmpxchg_memory_order order = memory_order_conservative);
 144 
 145   // Performs atomic compare of *dest and NULL, and replaces *dest
 146   // with exchange_value if the comparison succeeded.  Returns true if
 147   // the comparison succeeded and the exchange occurred.  This is
 148   // often used as part of lazy initialization, as a lock-free
 149   // alternative to the Double-Checked Locking Pattern.
 150   template<typename T, typename D>
 151   inline static bool replace_if_null(T* value, D* volatile* dest,
 152                                      cmpxchg_memory_order order = memory_order_conservative);
 153 
 154   inline static intptr_t cmpxchg_ptr(intptr_t exchange_value,
 155                                      volatile intptr_t* dest,
 156                                      intptr_t compare_value,
 157                                      cmpxchg_memory_order order = memory_order_conservative) {
 158     return cmpxchg(exchange_value, dest, compare_value, order);
 159   }
 160 
 161   inline static void* cmpxchg_ptr(void* exchange_value,
 162                                   volatile void* dest,
 163                                   void* compare_value,
 164                                   cmpxchg_memory_order order = memory_order_conservative) {
 165     return cmpxchg(exchange_value,
 166                    reinterpret_cast<void* volatile*>(dest),
 167                    compare_value,
 168                    order);
 169   }
 170 
 171 private:
 172   // Test whether From is implicitly convertible to To.
 173   // From and To must be pointer types.
 174   // Note: Provides the limited subset of C++11 std::is_convertible
 175   // that is needed here.
 176   template<typename From, typename To> struct IsPointerConvertible;
 177 
 178   // Dispatch handler for store.  Provides type-based validity
 179   // checking and limited conversions around calls to the platform-
 180   // specific implementation layer provided by PlatformOp.
 181   template<typename T, typename D, typename PlatformOp, typename Enable = void>
 182   struct StoreImpl;
 183 
 184   // Platform-specific implementation of store.  Support for sizes
 185   // of 1, 2, 4, and (if different) pointer size bytes are required.
 186   // The class is a function object that must be default constructable,
 187   // with these requirements:
 188   //
 189   // either:
 190   // - dest is of type D*, an integral, enum or pointer type.
 191   // - new_value are of type T, an integral, enum or pointer type D or
 192   //   pointer type convertible to D.
 193   // or:
 194   // - T and D are the same and are primitive convertible using PrimitiveConversions
 195   // and either way:
 196   // - platform_store is an object of type PlatformStore<sizeof(T)>.
 197   //
 198   // Then
 199   //   platform_store(new_value, dest)
 200   // must be a valid expression.
 201   //
 202   // The default implementation is a volatile store. If a platform
 203   // requires more for e.g. 64 bit stores, a specialization is required
 204   template<size_t byte_size> struct PlatformStore;
 205 
 206   // Dispatch handler for load.  Provides type-based validity
 207   // checking and limited conversions around calls to the platform-
 208   // specific implementation layer provided by PlatformOp.
 209   template<typename T, typename PlatformOp, typename Enable = void>
 210   struct LoadImpl;
 211 
 212   // Platform-specific implementation of load. Support for sizes of
 213   // 1, 2, 4 bytes and (if different) pointer size bytes are required.
 214   // The class is a function object that must be default
 215   // constructable, with these requirements:
 216   //
 217   // - dest is of type T*, an integral, enum or pointer type, or
 218   //   T is convertible to a primitive type using PrimitiveConversions
 219   // - platform_load is an object of type PlatformLoad<sizeof(T)>.
 220   //
 221   // Then
 222   //   platform_load(src)
 223   // must be a valid expression, returning a result convertible to T.
 224   //
 225   // The default implementation is a volatile load. If a platform
 226   // requires more for e.g. 64 bit loads, a specialization is required
 227   template<size_t byte_size> struct PlatformLoad;
 228 
 229   // Dispatch handler for add.  Provides type-based validity checking
 230   // and limited conversions around calls to the platform-specific
 231   // implementation layer provided by PlatformAdd.
 232   template<typename I, typename D, typename Enable = void>
 233   struct AddImpl;
 234 
 235   // Platform-specific implementation of add.  Support for sizes of 4
 236   // bytes and (if different) pointer size bytes are required.  The
 237   // class is a function object that must be default constructable,
 238   // with these requirements:
 239   //
 240   // - dest is of type D*, an integral or pointer type.
 241   // - add_value is of type I, an integral type.
 242   // - sizeof(I) == sizeof(D).
 243   // - if D is an integral type, I == D.
 244   // - platform_add is an object of type PlatformAdd<sizeof(D)>.
 245   //
 246   // Then
 247   //   platform_add(add_value, dest)
 248   // must be a valid expression, returning a result convertible to D.
 249   //
 250   // No definition is provided; all platforms must explicitly define
 251   // this class and any needed specializations.
 252   template<size_t byte_size> struct PlatformAdd;
 253 
 254   // Helper base classes for defining PlatformAdd.  To use, define
 255   // PlatformAdd or a specialization that derives from one of these,
 256   // and include in the PlatformAdd definition the support function
 257   // (described below) required by the base class.
 258   //
 259   // These classes implement the required function object protocol for
 260   // PlatformAdd, using a support function template provided by the
 261   // derived class.  Let add_value (of type I) and dest (of type D) be
 262   // the arguments the object is called with.  If D is a pointer type
 263   // P*, then let addend (of type I) be add_value * sizeof(P);
 264   // otherwise, addend is add_value.
 265   //
 266   // FetchAndAdd requires the derived class to provide
 267   //   fetch_and_add(addend, dest)
 268   // atomically adding addend to the value of dest, and returning the
 269   // old value.
 270   //
 271   // AddAndFetch requires the derived class to provide
 272   //   add_and_fetch(addend, dest)
 273   // atomically adding addend to the value of dest, and returning the
 274   // new value.
 275   //
 276   // When D is a pointer type P*, both fetch_and_add and add_and_fetch
 277   // treat it as if it were a uintptr_t; they do not perform any
 278   // scaling of the addend, as that has already been done by the
 279   // caller.
 280 public: // Temporary, can't be private: C++03 11.4/2. Fixed by C++11.
 281   template<typename Derived> struct FetchAndAdd;
 282   template<typename Derived> struct AddAndFetch;
 283 private:
 284 
 285   // Support for platforms that implement some variants of add using a
 286   // (typically out of line) non-template helper function.  The
 287   // generic arguments passed to PlatformAdd need to be translated to
 288   // the appropriate type for the helper function, the helper function
 289   // invoked on the translated arguments, and the result translated
 290   // back.  Type is the parameter / return type of the helper
 291   // function.  No scaling of add_value is performed when D is a pointer
 292   // type, so this function can be used to implement the support function
 293   // required by AddAndFetch.
 294   template<typename Type, typename Fn, typename I, typename D>
 295   static D add_using_helper(Fn fn, I add_value, D volatile* dest);
 296 
 297   // Dispatch handler for cmpxchg.  Provides type-based validity
 298   // checking and limited conversions around calls to the
 299   // platform-specific implementation layer provided by
 300   // PlatformCmpxchg.
 301   template<typename T, typename D, typename U, typename Enable = void>
 302   struct CmpxchgImpl;
 303 
 304   // Platform-specific implementation of cmpxchg.  Support for sizes
 305   // of 1, 4, and 8 are required.  The class is a function object that
 306   // must be default constructable, with these requirements:
 307   //
 308   // - dest is of type T*.
 309   // - exchange_value and compare_value are of type T.
 310   // - order is of type cmpxchg_memory_order.
 311   // - platform_cmpxchg is an object of type PlatformCmpxchg<sizeof(T)>.
 312   //
 313   // Then
 314   //   platform_cmpxchg(exchange_value, dest, compare_value, order)
 315   // must be a valid expression, returning a result convertible to T.
 316   //
 317   // A default definition is provided, which declares a function template
 318   //   T operator()(T, T volatile*, T, cmpxchg_memory_order) const
 319   //
 320   // For each required size, a platform must either provide an
 321   // appropriate definition of that function, or must entirely
 322   // specialize the class template for that size.
 323   template<size_t byte_size> struct PlatformCmpxchg;
 324 
 325   // Support for platforms that implement some variants of cmpxchg
 326   // using a (typically out of line) non-template helper function.
 327   // The generic arguments passed to PlatformCmpxchg need to be
 328   // translated to the appropriate type for the helper function, the
 329   // helper invoked on the translated arguments, and the result
 330   // translated back.  Type is the parameter / return type of the
 331   // helper function.
 332   template<typename Type, typename Fn, typename T>
 333   static T cmpxchg_using_helper(Fn fn,
 334                                 T exchange_value,
 335                                 T volatile* dest,
 336                                 T compare_value);
 337 
 338   // Support platforms that do not provide Read-Modify-Write
 339   // byte-level atomic access. To use, derive PlatformCmpxchg<1> from
 340   // this class.
 341 public: // Temporary, can't be private: C++03 11.4/2. Fixed by C++11.
 342   struct CmpxchgByteUsingInt;
 343 private:
 344 
 345   // Dispatch handler for xchg.  Provides type-based validity
 346   // checking and limited conversions around calls to the
 347   // platform-specific implementation layer provided by
 348   // PlatformXchg.
 349   template<typename T, typename D, typename Enable = void>
 350   struct XchgImpl;
 351 
 352   // Platform-specific implementation of xchg.  Support for sizes
 353   // of 4, and sizeof(intptr_t) are required.  The class is a function
 354   // object that must be default constructable, with these requirements:
 355   //
 356   // - dest is of type T*.
 357   // - exchange_value is of type T.
 358   // - platform_xchg is an object of type PlatformXchg<sizeof(T)>.
 359   //
 360   // Then
 361   //   platform_xchg(exchange_value, dest)
 362   // must be a valid expression, returning a result convertible to T.
 363   //
 364   // A default definition is provided, which declares a function template
 365   //   T operator()(T, T volatile*, T, cmpxchg_memory_order) const
 366   //
 367   // For each required size, a platform must either provide an
 368   // appropriate definition of that function, or must entirely
 369   // specialize the class template for that size.
 370   template<size_t byte_size> struct PlatformXchg;
 371 
 372   // Support for platforms that implement some variants of xchg
 373   // using a (typically out of line) non-template helper function.
 374   // The generic arguments passed to PlatformXchg need to be
 375   // translated to the appropriate type for the helper function, the
 376   // helper invoked on the translated arguments, and the result
 377   // translated back.  Type is the parameter / return type of the
 378   // helper function.
 379   template<typename Type, typename Fn, typename T>
 380   static T xchg_using_helper(Fn fn,
 381                              T exchange_value,
 382                              T volatile* dest);
 383 };
 384 
 385 template<typename From, typename To>
 386 struct Atomic::IsPointerConvertible<From*, To*> : AllStatic {
 387   // Determine whether From* is implicitly convertible to To*, using
 388   // the "sizeof trick".
 389   typedef char yes;
 390   typedef char (&no)[2];
 391 
 392   static yes test(To*);
 393   static no test(...);
 394   static From* test_value;
 395 
 396   static const bool value = (sizeof(yes) == sizeof(test(test_value)));
 397 };
 398 
 399 // Handle load for pointer, integral and enum types.
 400 template<typename T, typename PlatformOp>
 401 struct Atomic::LoadImpl<
 402   T,
 403   PlatformOp,
 404   typename EnableIf<IsIntegral<T>::value || IsRegisteredEnum<T>::value || IsPointer<T>::value>::type>
 405   VALUE_OBJ_CLASS_SPEC
 406 {
 407   T operator()(T const volatile* dest) const {
 408     // Forward to the platform handler for the size of T.
 409     return PlatformOp()(dest);
 410   }
 411 };
 412 
 413 // Handle load for types that have a translator.
 414 //
 415 // All the involved types must be identical.
 416 //
 417 // This translates the original call into a call on the decayed
 418 // arguments, and returns the recovered result of that translated
 419 // call.
 420 template<typename T, typename PlatformOp>
 421 struct Atomic::LoadImpl<
 422   T,
 423   PlatformOp,
 424   typename EnableIf<PrimitiveConversions::Translate<T>::value>::type>
 425   VALUE_OBJ_CLASS_SPEC
 426 {
 427   T operator()(T const volatile* dest) const {
 428     typedef PrimitiveConversions::Translate<T> Translator;
 429     typedef typename Translator::Decayed Decayed;
 430     STATIC_ASSERT(sizeof(T) == sizeof(Decayed));
 431     Decayed result = PlatformOp()(reinterpret_cast<Decayed const volatile*>(dest));
 432     return Translator::recover(result);
 433   }
 434 };
 435 
 436 // Default implementation of atomic load if a specific platform
 437 // does not provide a specialization for a certain size class.
 438 // For increased safety, the default implementation only allows
 439 // load types that are pointer sized or smaller. If a platform still
 440 // supports wide atomics, then it has to use specialization
 441 // of Atomic::PlatformLoad for that wider size class.
 442 template<size_t byte_size>
 443 struct Atomic::PlatformLoad VALUE_OBJ_CLASS_SPEC {
 444   template<typename T>
 445   T operator()(T const volatile* dest) const {
 446     STATIC_ASSERT(sizeof(T) <= sizeof(void*)); // wide atomics need specialization
 447     return *dest;
 448   }
 449 };
 450 
 451 // Handle store for integral and enum types.
 452 //
 453 // All the involved types must be identical.
 454 template<typename T, typename PlatformOp>
 455 struct Atomic::StoreImpl<
 456   T, T,
 457   PlatformOp,
 458   typename EnableIf<IsIntegral<T>::value || IsRegisteredEnum<T>::value>::type>
 459   VALUE_OBJ_CLASS_SPEC
 460 {
 461   void operator()(T new_value, T volatile* dest) const {
 462     // Forward to the platform handler for the size of T.
 463     PlatformOp()(new_value, dest);
 464   }
 465 };
 466 
 467 // Handle store for pointer types.
 468 //
 469 // The new_value must be implicitly convertible to the
 470 // destination's type; it must be type-correct to store the
 471 // new_value in the destination.
 472 template<typename T, typename D, typename PlatformOp>
 473 struct Atomic::StoreImpl<
 474   T*, D*,
 475   PlatformOp,
 476   typename EnableIf<Atomic::IsPointerConvertible<T*, D*>::value>::type>
 477   VALUE_OBJ_CLASS_SPEC
 478 {
 479   void operator()(T* new_value, D* volatile* dest) const {
 480     // Allow derived to base conversion, and adding cv-qualifiers.
 481     D* value = new_value;
 482     PlatformOp()(value, dest);
 483   }
 484 };
 485 
 486 // Handle store for types that have a translator.
 487 //
 488 // All the involved types must be identical.
 489 //
 490 // This translates the original call into a call on the decayed
 491 // arguments.
 492 template<typename T, typename PlatformOp>
 493 struct Atomic::StoreImpl<
 494   T, T,
 495   PlatformOp,
 496   typename EnableIf<PrimitiveConversions::Translate<T>::value>::type>
 497   VALUE_OBJ_CLASS_SPEC
 498 {
 499   void operator()(T new_value, T volatile* dest) const {
 500     typedef PrimitiveConversions::Translate<T> Translator;
 501     typedef typename Translator::Decayed Decayed;
 502     STATIC_ASSERT(sizeof(T) == sizeof(Decayed));
 503     PlatformOp()(Translator::decay(new_value),
 504                  reinterpret_cast<Decayed volatile*>(dest));
 505   }
 506 };
 507 
 508 // Default implementation of atomic store if a specific platform
 509 // does not provide a specialization for a certain size class.
 510 // For increased safety, the default implementation only allows
 511 // storing types that are pointer sized or smaller. If a platform still
 512 // supports wide atomics, then it has to use specialization
 513 // of Atomic::PlatformStore for that wider size class.
 514 template<size_t byte_size>
 515 struct Atomic::PlatformStore VALUE_OBJ_CLASS_SPEC {
 516   template<typename T>
 517   void operator()(T new_value,
 518                   T volatile* dest) const {
 519     STATIC_ASSERT(sizeof(T) <= sizeof(void*)); // wide atomics need specialization
 520     (void)const_cast<T&>(*dest = new_value);
 521   }
 522 };
 523 
 524 // Define FetchAndAdd and AddAndFetch helper classes before including
 525 // platform file, which may use these as base classes, requiring they
 526 // be complete.
 527 
 528 template<typename Derived>
 529 struct Atomic::FetchAndAdd VALUE_OBJ_CLASS_SPEC {
 530   template<typename I, typename D>
 531   D operator()(I add_value, D volatile* dest) const;
 532 };
 533 
 534 template<typename Derived>
 535 struct Atomic::AddAndFetch VALUE_OBJ_CLASS_SPEC {
 536   template<typename I, typename D>
 537   D operator()(I add_value, D volatile* dest) const;
 538 };
 539 
 540 template<typename D>
 541 inline void Atomic::inc(D volatile* dest) {
 542   STATIC_ASSERT(IsPointer<D>::value || IsIntegral<D>::value);
 543   typedef typename Conditional<IsPointer<D>::value, ptrdiff_t, D>::type I;
 544   Atomic::add(I(1), dest);
 545 }
 546 
 547 template<typename D>
 548 inline void Atomic::dec(D volatile* dest) {
 549   STATIC_ASSERT(IsPointer<D>::value || IsIntegral<D>::value);
 550   typedef typename Conditional<IsPointer<D>::value, ptrdiff_t, D>::type I;
 551   // Assumes two's complement integer representation.
 552   #pragma warning(suppress: 4146)
 553   Atomic::add(I(-1), dest);
 554 }
 555 
 556 // Define the class before including platform file, which may specialize
 557 // the operator definition.  No generic definition of specializations
 558 // of the operator template are provided, nor are there any generic
 559 // specializations of the class.  The platform file is responsible for
 560 // providing those.
 561 template<size_t byte_size>
 562 struct Atomic::PlatformCmpxchg VALUE_OBJ_CLASS_SPEC {
 563   template<typename T>
 564   T operator()(T exchange_value,
 565                T volatile* dest,
 566                T compare_value,
 567                cmpxchg_memory_order order) const;
 568 };
 569 
 570 // Define the class before including platform file, which may use this
 571 // as a base class, requiring it be complete.  The definition is later
 572 // in this file, near the other definitions related to cmpxchg.
 573 struct Atomic::CmpxchgByteUsingInt VALUE_OBJ_CLASS_SPEC {
 574   template<typename T>
 575   T operator()(T exchange_value,
 576                T volatile* dest,
 577                T compare_value,
 578                cmpxchg_memory_order order) const;
 579 };
 580 
 581 // Define the class before including platform file, which may specialize
 582 // the operator definition.  No generic definition of specializations
 583 // of the operator template are provided, nor are there any generic
 584 // specializations of the class.  The platform file is responsible for
 585 // providing those.
 586 template<size_t byte_size>
 587 struct Atomic::PlatformXchg VALUE_OBJ_CLASS_SPEC {
 588   template<typename T>
 589   T operator()(T exchange_value,
 590                T volatile* dest) const;
 591 };
 592 
 593 // platform specific in-line definitions - must come before shared definitions
 594 
 595 #include OS_CPU_HEADER(atomic)
 596 
 597 // shared in-line definitions
 598 
 599 // size_t casts...
 600 #if (SIZE_MAX != UINTPTR_MAX)
 601 #error size_t is not WORD_SIZE, interesting platform, but missing implementation here
 602 #endif
 603 
 604 template<typename T>
 605 inline T Atomic::load(const volatile T* dest) {
 606   return LoadImpl<T, PlatformLoad<sizeof(T)> >()(dest);
 607 }
 608 
 609 template<typename T, typename D>
 610 inline void Atomic::store(T store_value, volatile D* dest) {
 611   StoreImpl<T, D, PlatformStore<sizeof(D)> >()(store_value, dest);
 612 }
 613 
 614 template<typename I, typename D>
 615 inline D Atomic::add(I add_value, D volatile* dest) {
 616   return AddImpl<I, D>()(add_value, dest);
 617 }
 618 
 619 template<typename I, typename D>
 620 struct Atomic::AddImpl<
 621   I, D,
 622   typename EnableIf<IsIntegral<I>::value &&
 623                     IsIntegral<D>::value &&
 624                     (sizeof(I) <= sizeof(D)) &&
 625                     (IsSigned<I>::value == IsSigned<D>::value)>::type>
 626   VALUE_OBJ_CLASS_SPEC
 627 {
 628   D operator()(I add_value, D volatile* dest) const {
 629     D addend = add_value;
 630     return PlatformAdd<sizeof(D)>()(addend, dest);
 631   }
 632 };
 633 
 634 template<typename I, typename P>
 635 struct Atomic::AddImpl<
 636   I, P*,
 637   typename EnableIf<IsIntegral<I>::value && (sizeof(I) <= sizeof(P*))>::type>
 638   VALUE_OBJ_CLASS_SPEC
 639 {
 640   P* operator()(I add_value, P* volatile* dest) const {
 641     STATIC_ASSERT(sizeof(intptr_t) == sizeof(P*));
 642     STATIC_ASSERT(sizeof(uintptr_t) == sizeof(P*));
 643     typedef typename Conditional<IsSigned<I>::value,
 644                                  intptr_t,
 645                                  uintptr_t>::type CI;
 646     CI addend = add_value;
 647     return PlatformAdd<sizeof(P*)>()(addend, dest);
 648   }
 649 };
 650 
 651 // Most platforms do not support atomic add on a 2-byte value. However,
 652 // if the value occupies the most significant 16 bits of an aligned 32-bit
 653 // word, then we can do this with an atomic add of (add_value << 16)
 654 // to the 32-bit word.
 655 //
 656 // The least significant parts of this 32-bit word will never be affected, even
 657 // in case of overflow/underflow.
 658 //
 659 // Use the ATOMIC_SHORT_PAIR macro (see macros.hpp) to get the desired alignment.
 660 template<>
 661 struct Atomic::AddImpl<jshort, jshort> VALUE_OBJ_CLASS_SPEC {
 662   jshort operator()(jshort add_value, jshort volatile* dest) const {
 663 #ifdef VM_LITTLE_ENDIAN
 664     assert((intx(dest) & 0x03) == 0x02, "wrong alignment");
 665     jint new_value = Atomic::add(add_value << 16, (volatile jint*)(dest-1));
 666 #else
 667     assert((intx(dest) & 0x03) == 0x00, "wrong alignment");
 668     jint new_value = Atomic::add(add_value << 16, (volatile jint*)(dest));
 669 #endif
 670     return (jshort)(new_value >> 16); // preserves sign
 671   }
 672 };
 673 
 674 template<typename Derived>
 675 template<typename I, typename D>
 676 inline D Atomic::FetchAndAdd<Derived>::operator()(I add_value, D volatile* dest) const {
 677   I addend = add_value;
 678   // If D is a pointer type P*, scale by sizeof(P).
 679   if (IsPointer<D>::value) {
 680     addend *= sizeof(typename RemovePointer<D>::type);
 681   }
 682   D old = static_cast<const Derived*>(this)->fetch_and_add(addend, dest);
 683   return old + add_value;
 684 }
 685 
 686 template<typename Derived>
 687 template<typename I, typename D>
 688 inline D Atomic::AddAndFetch<Derived>::operator()(I add_value, D volatile* dest) const {
 689   // If D is a pointer type P*, scale by sizeof(P).
 690   if (IsPointer<D>::value) {
 691     add_value *= sizeof(typename RemovePointer<D>::type);
 692   }
 693   return static_cast<const Derived*>(this)->add_and_fetch(add_value, dest);
 694 }
 695 
 696 template<typename Type, typename Fn, typename I, typename D>
 697 inline D Atomic::add_using_helper(Fn fn, I add_value, D volatile* dest) {
 698   return PrimitiveConversions::cast<D>(
 699     fn(PrimitiveConversions::cast<Type>(add_value),
 700        reinterpret_cast<Type volatile*>(dest)));
 701 }
 702 
 703 template<typename T, typename D, typename U>
 704 inline D Atomic::cmpxchg(T exchange_value,
 705                          D volatile* dest,
 706                          U compare_value,
 707                          cmpxchg_memory_order order) {
 708   return CmpxchgImpl<T, D, U>()(exchange_value, dest, compare_value, order);
 709 }
 710 
 711 template<typename T, typename D>
 712 inline bool Atomic::replace_if_null(T* value, D* volatile* dest,
 713                                     cmpxchg_memory_order order) {
 714   // Presently using a trivial implementation in terms of cmpxchg.
 715   // Consider adding platform support, to permit the use of compiler
 716   // intrinsics like gcc's __sync_bool_compare_and_swap.
 717   D* expected_null = NULL;
 718   return expected_null == cmpxchg(value, dest, expected_null, order);
 719 }
 720 
 721 // Handle cmpxchg for integral and enum types.
 722 //
 723 // All the involved types must be identical.
 724 template<typename T>
 725 struct Atomic::CmpxchgImpl<
 726   T, T, T,
 727   typename EnableIf<IsIntegral<T>::value || IsRegisteredEnum<T>::value>::type>
 728   VALUE_OBJ_CLASS_SPEC
 729 {
 730   T operator()(T exchange_value, T volatile* dest, T compare_value,
 731                cmpxchg_memory_order order) const {
 732     // Forward to the platform handler for the size of T.
 733     return PlatformCmpxchg<sizeof(T)>()(exchange_value,
 734                                         dest,
 735                                         compare_value,
 736                                         order);
 737   }
 738 };
 739 
 740 // Handle cmpxchg for pointer types.
 741 //
 742 // The destination's type and the compare_value type must be the same,
 743 // ignoring cv-qualifiers; we don't care about the cv-qualifiers of
 744 // the compare_value.
 745 //
 746 // The exchange_value must be implicitly convertible to the
 747 // destination's type; it must be type-correct to store the
 748 // exchange_value in the destination.
 749 template<typename T, typename D, typename U>
 750 struct Atomic::CmpxchgImpl<
 751   T*, D*, U*,
 752   typename EnableIf<Atomic::IsPointerConvertible<T*, D*>::value &&
 753                     IsSame<typename RemoveCV<D>::type,
 754                            typename RemoveCV<U>::type>::value>::type>
 755   VALUE_OBJ_CLASS_SPEC
 756 {
 757   D* operator()(T* exchange_value, D* volatile* dest, U* compare_value,
 758                cmpxchg_memory_order order) const {
 759     // Allow derived to base conversion, and adding cv-qualifiers.
 760     D* new_value = exchange_value;
 761     // Don't care what the CV qualifiers for compare_value are,
 762     // but we need to match D* when calling platform support.
 763     D* old_value = const_cast<D*>(compare_value);
 764     return PlatformCmpxchg<sizeof(D*)>()(new_value, dest, old_value, order);
 765   }
 766 };
 767 
 768 // Handle cmpxchg for types that have a translator.
 769 //
 770 // All the involved types must be identical.
 771 //
 772 // This translates the original call into a call on the decayed
 773 // arguments, and returns the recovered result of that translated
 774 // call.
 775 template<typename T>
 776 struct Atomic::CmpxchgImpl<
 777   T, T, T,
 778   typename EnableIf<PrimitiveConversions::Translate<T>::value>::type>
 779   VALUE_OBJ_CLASS_SPEC
 780 {
 781   T operator()(T exchange_value, T volatile* dest, T compare_value,
 782                cmpxchg_memory_order order) const {
 783     typedef PrimitiveConversions::Translate<T> Translator;
 784     typedef typename Translator::Decayed Decayed;
 785     STATIC_ASSERT(sizeof(T) == sizeof(Decayed));
 786     return Translator::recover(
 787       cmpxchg(Translator::decay(exchange_value),
 788               reinterpret_cast<Decayed volatile*>(dest),
 789               Translator::decay(compare_value),
 790               order));
 791   }
 792 };
 793 
 794 template<typename Type, typename Fn, typename T>
 795 inline T Atomic::cmpxchg_using_helper(Fn fn,
 796                                       T exchange_value,
 797                                       T volatile* dest,
 798                                       T compare_value) {
 799   STATIC_ASSERT(sizeof(Type) == sizeof(T));
 800   return PrimitiveConversions::cast<T>(
 801     fn(PrimitiveConversions::cast<Type>(exchange_value),
 802        reinterpret_cast<Type volatile*>(dest),
 803        PrimitiveConversions::cast<Type>(compare_value)));
 804 }
 805 
 806 template<typename T>
 807 inline T Atomic::CmpxchgByteUsingInt::operator()(T exchange_value,
 808                                                  T volatile* dest,
 809                                                  T compare_value,
 810                                                  cmpxchg_memory_order order) const {
 811   STATIC_ASSERT(sizeof(T) == sizeof(uint8_t));
 812   uint8_t canon_exchange_value = exchange_value;
 813   uint8_t canon_compare_value = compare_value;
 814   volatile uint32_t* aligned_dest
 815     = reinterpret_cast<volatile uint32_t*>(align_down(dest, sizeof(uint32_t)));
 816   size_t offset = pointer_delta(dest, aligned_dest, 1);
 817   uint32_t cur = *aligned_dest;
 818   uint8_t* cur_as_bytes = reinterpret_cast<uint8_t*>(&cur);
 819 
 820   // current value may not be what we are looking for, so force it
 821   // to that value so the initial cmpxchg will fail if it is different
 822   cur_as_bytes[offset] = canon_compare_value;
 823 
 824   // always execute a real cmpxchg so that we get the required memory
 825   // barriers even on initial failure
 826   do {
 827     // value to swap in matches current value ...
 828     uint32_t new_value = cur;
 829     // ... except for the one jbyte we want to update
 830     reinterpret_cast<uint8_t*>(&new_value)[offset] = canon_exchange_value;
 831 
 832     uint32_t res = cmpxchg(new_value, aligned_dest, cur, order);
 833     if (res == cur) break;      // success
 834 
 835     // at least one byte in the int changed value, so update
 836     // our view of the current int
 837     cur = res;
 838     // if our byte is still as cur we loop and try again
 839   } while (cur_as_bytes[offset] == canon_compare_value);
 840 
 841   return PrimitiveConversions::cast<T>(cur_as_bytes[offset]);
 842 }
 843 
 844 // Handle xchg for integral and enum types.
 845 //
 846 // All the involved types must be identical.
 847 template<typename T>
 848 struct Atomic::XchgImpl<
 849   T, T,
 850   typename EnableIf<IsIntegral<T>::value || IsRegisteredEnum<T>::value>::type>
 851   VALUE_OBJ_CLASS_SPEC
 852 {
 853   T operator()(T exchange_value, T volatile* dest) const {
 854     // Forward to the platform handler for the size of T.
 855     return PlatformXchg<sizeof(T)>()(exchange_value, dest);
 856   }
 857 };
 858 
 859 // Handle xchg for pointer types.
 860 //
 861 // The exchange_value must be implicitly convertible to the
 862 // destination's type; it must be type-correct to store the
 863 // exchange_value in the destination.
 864 template<typename T, typename D>
 865 struct Atomic::XchgImpl<
 866   T*, D*,
 867   typename EnableIf<Atomic::IsPointerConvertible<T*, D*>::value>::type>
 868   VALUE_OBJ_CLASS_SPEC
 869 {
 870   D* operator()(T* exchange_value, D* volatile* dest) const {
 871     // Allow derived to base conversion, and adding cv-qualifiers.
 872     D* new_value = exchange_value;
 873     return PlatformXchg<sizeof(D*)>()(new_value, dest);
 874   }
 875 };
 876 
 877 // Handle xchg for types that have a translator.
 878 //
 879 // All the involved types must be identical.
 880 //
 881 // This translates the original call into a call on the decayed
 882 // arguments, and returns the recovered result of that translated
 883 // call.
 884 template<typename T>
 885 struct Atomic::XchgImpl<
 886   T, T,
 887   typename EnableIf<PrimitiveConversions::Translate<T>::value>::type>
 888   VALUE_OBJ_CLASS_SPEC
 889 {
 890   T operator()(T exchange_value, T volatile* dest) const {
 891     typedef PrimitiveConversions::Translate<T> Translator;
 892     typedef typename Translator::Decayed Decayed;
 893     STATIC_ASSERT(sizeof(T) == sizeof(Decayed));
 894     return Translator::recover(
 895       xchg(Translator::decay(exchange_value),
 896            reinterpret_cast<Decayed volatile*>(dest)));
 897   }
 898 };
 899 
 900 template<typename Type, typename Fn, typename T>
 901 inline T Atomic::xchg_using_helper(Fn fn,
 902                                    T exchange_value,
 903                                    T volatile* dest) {
 904   STATIC_ASSERT(sizeof(Type) == sizeof(T));
 905   return PrimitiveConversions::cast<T>(
 906     fn(PrimitiveConversions::cast<Type>(exchange_value),
 907        reinterpret_cast<Type volatile*>(dest)));
 908 }
 909 
 910 template<typename T, typename D>
 911 inline D Atomic::xchg(T exchange_value, volatile D* dest) {
 912   return XchgImpl<T, D>()(exchange_value, dest);
 913 }
 914 
 915 #endif // SHARE_VM_RUNTIME_ATOMIC_HPP