-/// getMallocArraySize - Returns the array size of a malloc call. For array
-/// mallocs, the size is computated in 1 of 3 ways:
-/// 1. If the element type is of size 1, then array size is the argument to
-/// malloc.
-/// 2. Else if the malloc's argument is a constant, the array size is that
-/// argument divided by the element type's size.
-/// 3. Else the malloc argument must be a multiplication and the array size is
-/// the first operand of the multiplication.
-/// For non-array mallocs, the computed size is constant 1.
-/// This function returns NULL for all mallocs whose array size cannot be
-/// determined.
-Value* llvm::getMallocArraySize(CallInst* CI, LLVMContext &Context,
- const TargetData* TD) {
- if (!isSafeToGetMallocArraySize(CI, Context, TD))
- return NULL;
-
- // Match CreateMalloc's use of constant 1 array-size for non-array mallocs.
- if (!isArrayMalloc(CI, Context, TD))
- return ConstantInt::get(CI->getOperand(1)->getType(), 1);
-
- Value* MallocArg = CI->getOperand(1);
- assert(getMallocAllocatedType(CI) && "getMallocArraySize and no type");
- Constant *ElementSize = ConstantExpr::getSizeOf(getMallocAllocatedType(CI));
- ElementSize = ConstantExpr::getTruncOrBitCast(ElementSize,
- MallocArg->getType());
-
- Constant* CO = dyn_cast<Constant>(MallocArg);
- BinaryOperator* BO = dyn_cast<BinaryOperator>(MallocArg);
- assert((isConstantOne(ElementSize) || CO || BO) &&
- "getMallocArraySize and malformed malloc IR");
-
- if (isConstantOne(ElementSize))
- return MallocArg;
-
- if (CO)
- return CO->getOperand(0);
-
- // TODO: Detect case where MallocArg mul has been transformed to shl.
-
- assert(BO && "getMallocArraySize not constant but not multiplication either");
- return BO->getOperand(0);
-}