Max Wang Max Wang - 1 month ago 9
Objective-C Question

inline bool objc_object::isTaggedPointer(); How does the function work?

When I read runtime,

I can't understand how does the function work.

inline bool
objc_object::isTaggedPointer()
{
return ((uintptr_t)this & TAG_MASK);
}


Below are how TAG_MASK define:

#if SUPPORT_MSB_TAGGED_POINTERS
# define TAG_MASK (1ULL<<63)
# define TAG_SLOT_SHIFT 60
# define TAG_PAYLOAD_LSHIFT 4
# define TAG_PAYLOAD_RSHIFT 4
#else
# define TAG_MASK 1
# define TAG_SLOT_SHIFT 0
# define TAG_PAYLOAD_LSHIFT 0
# define TAG_PAYLOAD_RSHIFT 4
#endif


I know if TAG_MASK equals to 1,the function return false.But When the function return true and why this function can judge the result.
Thanks!

Answer

A tagged pointer is a way to create an object without an allocation.

Thus, the runtime needs to be able to detect if an object is a reference to a chunk of allocated memory or if the object pointer is really data.

It does this by setting one bit in the "pointer" to 1. A bit that normally would always be 0 for regular allocations. There are two modes; "most significant bit" and "least significant bit".

In the LSB model, the first bit is used. When allocating memory, all allocations are even aligned and, thus, the low order bit should never be zero. By setting it to zero, the runtime can key on that to detect tagged pointers. The MSB model moves the bit to the highest slot (which is safe because no one should ever map memory into a region with the highest bit set).

isTaggedPointer() returns YES/true if the lowest bit is set in the LSB model and YES/true if the highest bit is set in the MSB model.