LLVM  6.0.0svn
MemoryBuiltins.cpp
Go to the documentation of this file.
1 //===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This family of functions identifies calls to builtin functions that allocate
11 // or free memory.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/Statistic.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Intrinsics.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Support/Debug.h"
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "memory-builtins"
33 
34 enum AllocType : uint8_t {
35  OpNewLike = 1<<0, // allocates; never returns null
36  MallocLike = 1<<1 | OpNewLike, // allocates; may return null
37  CallocLike = 1<<2, // allocates + bzero
38  ReallocLike = 1<<3, // reallocates
39  StrDupLike = 1<<4,
43 };
44 
45 struct AllocFnsTy {
47  unsigned NumParams;
48  // First and Second size parameters (or -1 if unused)
49  int FstParam, SndParam;
50 };
51 
52 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
53 // know which functions are nounwind, noalias, nocapture parameters, etc.
54 static const std::pair<LibFunc, AllocFnsTy> AllocationFnData[] = {
55  {LibFunc_malloc, {MallocLike, 1, 0, -1}},
56  {LibFunc_valloc, {MallocLike, 1, 0, -1}},
57  {LibFunc_Znwj, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
58  {LibFunc_ZnwjRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
59  {LibFunc_Znwm, {OpNewLike, 1, 0, -1}}, // new(unsigned long)
60  {LibFunc_ZnwmRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned long, nothrow)
61  {LibFunc_Znaj, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
62  {LibFunc_ZnajRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
63  {LibFunc_Znam, {OpNewLike, 1, 0, -1}}, // new[](unsigned long)
64  {LibFunc_ZnamRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned long, nothrow)
65  {LibFunc_msvc_new_int, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
66  {LibFunc_msvc_new_int_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
67  {LibFunc_msvc_new_longlong, {OpNewLike, 1, 0, -1}}, // new(unsigned long long)
68  {LibFunc_msvc_new_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned long long, nothrow)
69  {LibFunc_msvc_new_array_int, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
70  {LibFunc_msvc_new_array_int_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
71  {LibFunc_msvc_new_array_longlong, {OpNewLike, 1, 0, -1}}, // new[](unsigned long long)
72  {LibFunc_msvc_new_array_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned long long, nothrow)
73  {LibFunc_calloc, {CallocLike, 2, 0, 1}},
74  {LibFunc_realloc, {ReallocLike, 2, 1, -1}},
75  {LibFunc_reallocf, {ReallocLike, 2, 1, -1}},
76  {LibFunc_strdup, {StrDupLike, 1, -1, -1}},
77  {LibFunc_strndup, {StrDupLike, 2, 1, -1}}
78  // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
79 };
80 
81 static const Function *getCalledFunction(const Value *V, bool LookThroughBitCast,
82  bool &IsNoBuiltin) {
83  // Don't care about intrinsics in this case.
84  if (isa<IntrinsicInst>(V))
85  return nullptr;
86 
87  if (LookThroughBitCast)
88  V = V->stripPointerCasts();
89 
90  ImmutableCallSite CS(V);
91  if (!CS.getInstruction())
92  return nullptr;
93 
94  IsNoBuiltin = CS.isNoBuiltin();
95 
96  const Function *Callee = CS.getCalledFunction();
97  if (!Callee || !Callee->isDeclaration())
98  return nullptr;
99  return Callee;
100 }
101 
102 /// Returns the allocation data for the given value if it's either a call to a
103 /// known allocation function, or a call to a function with the allocsize
104 /// attribute.
107  const TargetLibraryInfo *TLI) {
108  // Make sure that the function is available.
109  StringRef FnName = Callee->getName();
110  LibFunc TLIFn;
111  if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
112  return None;
113 
114  const auto *Iter = find_if(
115  AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) {
116  return P.first == TLIFn;
117  });
118 
119  if (Iter == std::end(AllocationFnData))
120  return None;
121 
122  const AllocFnsTy *FnData = &Iter->second;
123  if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
124  return None;
125 
126  // Check function prototype.
127  int FstParam = FnData->FstParam;
128  int SndParam = FnData->SndParam;
129  FunctionType *FTy = Callee->getFunctionType();
130 
131  if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
132  FTy->getNumParams() == FnData->NumParams &&
133  (FstParam < 0 ||
134  (FTy->getParamType(FstParam)->isIntegerTy(32) ||
135  FTy->getParamType(FstParam)->isIntegerTy(64))) &&
136  (SndParam < 0 ||
137  FTy->getParamType(SndParam)->isIntegerTy(32) ||
138  FTy->getParamType(SndParam)->isIntegerTy(64)))
139  return *FnData;
140  return None;
141 }
142 
144  const TargetLibraryInfo *TLI,
145  bool LookThroughBitCast = false) {
146  bool IsNoBuiltinCall;
147  if (const Function *Callee =
148  getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
149  if (!IsNoBuiltinCall)
150  return getAllocationDataForFunction(Callee, AllocTy, TLI);
151  return None;
152 }
153 
155  const TargetLibraryInfo *TLI) {
156  bool IsNoBuiltinCall;
157  const Function *Callee =
158  getCalledFunction(V, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
159  if (!Callee)
160  return None;
161 
162  // Prefer to use existing information over allocsize. This will give us an
163  // accurate AllocTy.
164  if (!IsNoBuiltinCall)
167  return Data;
168 
169  Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
170  if (Attr == Attribute())
171  return None;
172 
173  std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
174 
175  AllocFnsTy Result;
176  // Because allocsize only tells us how many bytes are allocated, we're not
177  // really allowed to assume anything, so we use MallocLike.
178  Result.AllocTy = MallocLike;
179  Result.NumParams = Callee->getNumOperands();
180  Result.FstParam = Args.first;
181  Result.SndParam = Args.second.getValueOr(-1);
182  return Result;
183 }
184 
185 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
186  ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
187  return CS && CS.hasRetAttr(Attribute::NoAlias);
188 }
189 
190 
191 /// \brief Tests if a value is a call or invoke to a library function that
192 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
193 /// like).
194 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
195  bool LookThroughBitCast) {
196  return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue();
197 }
198 
199 /// \brief Tests if a value is a call or invoke to a function that returns a
200 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
201 bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
202  bool LookThroughBitCast) {
203  // it's safe to consider realloc as noalias since accessing the original
204  // pointer is undefined behavior
205  return isAllocationFn(V, TLI, LookThroughBitCast) ||
206  hasNoAliasAttr(V, LookThroughBitCast);
207 }
208 
209 /// \brief Tests if a value is a call or invoke to a library function that
210 /// allocates uninitialized memory (such as malloc).
211 bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
212  bool LookThroughBitCast) {
213  return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
214 }
215 
216 /// \brief Tests if a value is a call or invoke to a library function that
217 /// allocates zero-filled memory (such as calloc).
218 bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
219  bool LookThroughBitCast) {
220  return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
221 }
222 
223 /// \brief Tests if a value is a call or invoke to a library function that
224 /// allocates memory similiar to malloc or calloc.
226  bool LookThroughBitCast) {
227  return getAllocationData(V, MallocOrCallocLike, TLI,
228  LookThroughBitCast).hasValue();
229 }
230 
231 /// \brief Tests if a value is a call or invoke to a library function that
232 /// allocates memory (either malloc, calloc, or strdup like).
233 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
234  bool LookThroughBitCast) {
235  return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
236 }
237 
238 /// extractMallocCall - Returns the corresponding CallInst if the instruction
239 /// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
240 /// ignore InvokeInst here.
242  const TargetLibraryInfo *TLI) {
243  return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
244 }
245 
246 static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
247  const TargetLibraryInfo *TLI,
248  bool LookThroughSExt = false) {
249  if (!CI)
250  return nullptr;
251 
252  // The size of the malloc's result type must be known to determine array size.
253  Type *T = getMallocAllocatedType(CI, TLI);
254  if (!T || !T->isSized())
255  return nullptr;
256 
257  unsigned ElementSize = DL.getTypeAllocSize(T);
258  if (StructType *ST = dyn_cast<StructType>(T))
259  ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
260 
261  // If malloc call's arg can be determined to be a multiple of ElementSize,
262  // return the multiple. Otherwise, return NULL.
263  Value *MallocArg = CI->getArgOperand(0);
264  Value *Multiple = nullptr;
265  if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt))
266  return Multiple;
267 
268  return nullptr;
269 }
270 
271 /// getMallocType - Returns the PointerType resulting from the malloc call.
272 /// The PointerType depends on the number of bitcast uses of the malloc call:
273 /// 0: PointerType is the calls' return type.
274 /// 1: PointerType is the bitcast's result type.
275 /// >1: Unique PointerType cannot be determined, return NULL.
277  const TargetLibraryInfo *TLI) {
278  assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
279 
280  PointerType *MallocType = nullptr;
281  unsigned NumOfBitCastUses = 0;
282 
283  // Determine if CallInst has a bitcast use.
284  for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
285  UI != E;)
286  if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
287  MallocType = cast<PointerType>(BCI->getDestTy());
288  NumOfBitCastUses++;
289  }
290 
291  // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
292  if (NumOfBitCastUses == 1)
293  return MallocType;
294 
295  // Malloc call was not bitcast, so type is the malloc function's return type.
296  if (NumOfBitCastUses == 0)
297  return cast<PointerType>(CI->getType());
298 
299  // Type could not be determined.
300  return nullptr;
301 }
302 
303 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
304 /// The Type depends on the number of bitcast uses of the malloc call:
305 /// 0: PointerType is the malloc calls' return type.
306 /// 1: PointerType is the bitcast's result type.
307 /// >1: Unique PointerType cannot be determined, return NULL.
309  const TargetLibraryInfo *TLI) {
310  PointerType *PT = getMallocType(CI, TLI);
311  return PT ? PT->getElementType() : nullptr;
312 }
313 
314 /// getMallocArraySize - Returns the array size of a malloc call. If the
315 /// argument passed to malloc is a multiple of the size of the malloced type,
316 /// then return that multiple. For non-array mallocs, the multiple is
317 /// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
318 /// determined.
320  const TargetLibraryInfo *TLI,
321  bool LookThroughSExt) {
322  assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
323  return computeArraySize(CI, DL, TLI, LookThroughSExt);
324 }
325 
326 
327 /// extractCallocCall - Returns the corresponding CallInst if the instruction
328 /// is a calloc call.
330  const TargetLibraryInfo *TLI) {
331  return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
332 }
333 
334 
335 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
336 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
337  const CallInst *CI = dyn_cast<CallInst>(I);
338  if (!CI || isa<IntrinsicInst>(CI))
339  return nullptr;
340  Function *Callee = CI->getCalledFunction();
341  if (Callee == nullptr)
342  return nullptr;
343 
344  StringRef FnName = Callee->getName();
345  LibFunc TLIFn;
346  if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
347  return nullptr;
348 
349  unsigned ExpectedNumParams;
350  if (TLIFn == LibFunc_free ||
351  TLIFn == LibFunc_ZdlPv || // operator delete(void*)
352  TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
353  TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
354  TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
355  TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
356  TLIFn == LibFunc_msvc_delete_array_ptr64) // operator delete[](void*)
357  ExpectedNumParams = 1;
358  else if (TLIFn == LibFunc_ZdlPvj || // delete(void*, uint)
359  TLIFn == LibFunc_ZdlPvm || // delete(void*, ulong)
360  TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
361  TLIFn == LibFunc_ZdaPvj || // delete[](void*, uint)
362  TLIFn == LibFunc_ZdaPvm || // delete[](void*, ulong)
363  TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
364  TLIFn == LibFunc_msvc_delete_ptr32_int || // delete(void*, uint)
365  TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
366  TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
367  TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
368  TLIFn == LibFunc_msvc_delete_array_ptr32_int || // delete[](void*, uint)
369  TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
370  TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
371  TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow)
372  ExpectedNumParams = 2;
373  else
374  return nullptr;
375 
376  // Check free prototype.
377  // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
378  // attribute will exist.
379  FunctionType *FTy = Callee->getFunctionType();
380  if (!FTy->getReturnType()->isVoidTy())
381  return nullptr;
382  if (FTy->getNumParams() != ExpectedNumParams)
383  return nullptr;
384  if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
385  return nullptr;
386 
387  return CI;
388 }
389 
390 
391 
392 //===----------------------------------------------------------------------===//
393 // Utility functions to compute size of objects.
394 //
396  if (Data.second.isNegative() || Data.first.ult(Data.second))
397  return APInt(Data.first.getBitWidth(), 0);
398  return Data.first - Data.second;
399 }
400 
401 /// \brief Compute the size of the object pointed by Ptr. Returns true and the
402 /// object size in Size if successful, and false otherwise.
403 /// If RoundToAlign is true, then Size is rounded up to the alignment of
404 /// allocas, byval arguments, and global variables.
405 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
406  const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
407  ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
408  SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
409  if (!Visitor.bothKnown(Data))
410  return false;
411 
412  Size = getSizeWithOverflow(Data).getZExtValue();
413  return true;
414 }
415 
417  const DataLayout &DL,
418  const TargetLibraryInfo *TLI,
419  bool MustSucceed) {
420  assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
421  "ObjectSize must be a call to llvm.objectsize!");
422 
423  bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
424  ObjectSizeOpts EvalOptions;
425  // Unless we have to fold this to something, try to be as accurate as
426  // possible.
427  if (MustSucceed)
428  EvalOptions.EvalMode =
430  else
432 
433  EvalOptions.NullIsUnknownSize =
434  cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
435 
436  // FIXME: Does it make sense to just return a failure value if the size won't
437  // fit in the output and `!MustSucceed`?
438  uint64_t Size;
439  auto *ResultType = cast<IntegerType>(ObjectSize->getType());
440  if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
441  isUIntN(ResultType->getBitWidth(), Size))
442  return ConstantInt::get(ResultType, Size);
443 
444  if (!MustSucceed)
445  return nullptr;
446 
447  return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
448 }
449 
450 STATISTIC(ObjectVisitorArgument,
451  "Number of arguments with unsolved size and offset");
452 STATISTIC(ObjectVisitorLoad,
453  "Number of load instructions with unsolved size and offset");
454 
455 
456 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
457  if (Options.RoundToAlign && Align)
458  return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align));
459  return Size;
460 }
461 
463  const TargetLibraryInfo *TLI,
465  ObjectSizeOpts Options)
466  : DL(DL), TLI(TLI), Options(Options) {
467  // Pointer size must be rechecked for each object visited since it could have
468  // a different address space.
469 }
470 
472  IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
473  Zero = APInt::getNullValue(IntTyBits);
474 
475  V = V->stripPointerCasts();
476  if (Instruction *I = dyn_cast<Instruction>(V)) {
477  // If we have already seen this instruction, bail out. Cycles can happen in
478  // unreachable code after constant propagation.
479  if (!SeenInsts.insert(I).second)
480  return unknown();
481 
482  if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
483  return visitGEPOperator(*GEP);
484  return visit(*I);
485  }
486  if (Argument *A = dyn_cast<Argument>(V))
487  return visitArgument(*A);
488  if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
489  return visitConstantPointerNull(*P);
490  if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
491  return visitGlobalAlias(*GA);
492  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
493  return visitGlobalVariable(*GV);
494  if (UndefValue *UV = dyn_cast<UndefValue>(V))
495  return visitUndefValue(*UV);
496  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
497  if (CE->getOpcode() == Instruction::IntToPtr)
498  return unknown(); // clueless
499  if (CE->getOpcode() == Instruction::GetElementPtr)
500  return visitGEPOperator(cast<GEPOperator>(*CE));
501  }
502 
503  DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
504  << '\n');
505  return unknown();
506 }
507 
508 /// When we're compiling N-bit code, and the user uses parameters that are
509 /// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
510 /// trouble with APInt size issues. This function handles resizing + overflow
511 /// checks for us. Check and zext or trunc \p I depending on IntTyBits and
512 /// I's value.
513 bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
514  // More bits than we can handle. Checking the bit width isn't necessary, but
515  // it's faster than checking active bits, and should give `false` in the
516  // vast majority of cases.
517  if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
518  return false;
519  if (I.getBitWidth() != IntTyBits)
520  I = I.zextOrTrunc(IntTyBits);
521  return true;
522 }
523 
525  if (!I.getAllocatedType()->isSized())
526  return unknown();
527 
528  APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
529  if (!I.isArrayAllocation())
530  return std::make_pair(align(Size, I.getAlignment()), Zero);
531 
532  Value *ArraySize = I.getArraySize();
533  if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
534  APInt NumElems = C->getValue();
535  if (!CheckedZextOrTrunc(NumElems))
536  return unknown();
537 
538  bool Overflow;
539  Size = Size.umul_ov(NumElems, Overflow);
540  return Overflow ? unknown() : std::make_pair(align(Size, I.getAlignment()),
541  Zero);
542  }
543  return unknown();
544 }
545 
547  // No interprocedural analysis is done at the moment.
548  if (!A.hasByValOrInAllocaAttr()) {
549  ++ObjectVisitorArgument;
550  return unknown();
551  }
552  PointerType *PT = cast<PointerType>(A.getType());
553  APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
554  return std::make_pair(align(Size, A.getParamAlignment()), Zero);
555 }
556 
559  if (!FnData)
560  return unknown();
561 
562  // Handle strdup-like functions separately.
563  if (FnData->AllocTy == StrDupLike) {
564  APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
565  if (!Size)
566  return unknown();
567 
568  // Strndup limits strlen.
569  if (FnData->FstParam > 0) {
570  ConstantInt *Arg =
572  if (!Arg)
573  return unknown();
574 
575  APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
576  if (Size.ugt(MaxSize))
577  Size = MaxSize + 1;
578  }
579  return std::make_pair(Size, Zero);
580  }
581 
582  ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
583  if (!Arg)
584  return unknown();
585 
586  APInt Size = Arg->getValue();
587  if (!CheckedZextOrTrunc(Size))
588  return unknown();
589 
590  // Size is determined by just 1 parameter.
591  if (FnData->SndParam < 0)
592  return std::make_pair(Size, Zero);
593 
594  Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
595  if (!Arg)
596  return unknown();
597 
598  APInt NumElems = Arg->getValue();
599  if (!CheckedZextOrTrunc(NumElems))
600  return unknown();
601 
602  bool Overflow;
603  Size = Size.umul_ov(NumElems, Overflow);
604  return Overflow ? unknown() : std::make_pair(Size, Zero);
605 
606  // TODO: handle more standard functions (+ wchar cousins):
607  // - strdup / strndup
608  // - strcpy / strncpy
609  // - strcat / strncat
610  // - memcpy / memmove
611  // - strcat / strncat
612  // - memset
613 }
614 
617  if (Options.NullIsUnknownSize && CPN.getType()->getAddressSpace() == 0)
618  return unknown();
619  return std::make_pair(Zero, Zero);
620 }
621 
624  return unknown();
625 }
626 
629  // Easy cases were already folded by previous passes.
630  return unknown();
631 }
632 
634  SizeOffsetType PtrData = compute(GEP.getPointerOperand());
635  APInt Offset(IntTyBits, 0);
636  if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
637  return unknown();
638 
639  return std::make_pair(PtrData.first, PtrData.second + Offset);
640 }
641 
643  if (GA.isInterposable())
644  return unknown();
645  return compute(GA.getAliasee());
646 }
647 
649  if (!GV.hasDefinitiveInitializer())
650  return unknown();
651 
652  APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
653  return std::make_pair(align(Size, GV.getAlignment()), Zero);
654 }
655 
657  // clueless
658  return unknown();
659 }
660 
662  ++ObjectVisitorLoad;
663  return unknown();
664 }
665 
667  // too complex to analyze statically.
668  return unknown();
669 }
670 
672  SizeOffsetType TrueSide = compute(I.getTrueValue());
673  SizeOffsetType FalseSide = compute(I.getFalseValue());
674  if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
675  if (TrueSide == FalseSide) {
676  return TrueSide;
677  }
678 
679  APInt TrueResult = getSizeWithOverflow(TrueSide);
680  APInt FalseResult = getSizeWithOverflow(FalseSide);
681 
682  if (TrueResult == FalseResult) {
683  return TrueSide;
684  }
685  if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
686  if (TrueResult.slt(FalseResult))
687  return TrueSide;
688  return FalseSide;
689  }
690  if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
691  if (TrueResult.sgt(FalseResult))
692  return TrueSide;
693  return FalseSide;
694  }
695  }
696  return unknown();
697 }
698 
700  return std::make_pair(Zero, Zero);
701 }
702 
704  DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
705  return unknown();
706 }
707 
709  const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
710  bool RoundToAlign)
711  : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
712  RoundToAlign(RoundToAlign) {
713  // IntTy and Zero must be set for each compute() since the address space may
714  // be different for later objects.
715 }
716 
718  // XXX - Are vectors of pointers possible here?
719  IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
720  Zero = ConstantInt::get(IntTy, 0);
721 
722  SizeOffsetEvalType Result = compute_(V);
723 
724  if (!bothKnown(Result)) {
725  // Erase everything that was computed in this iteration from the cache, so
726  // that no dangling references are left behind. We could be a bit smarter if
727  // we kept a dependency graph. It's probably not worth the complexity.
728  for (const Value *SeenVal : SeenVals) {
729  CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
730  // non-computable results can be safely cached
731  if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
732  CacheMap.erase(CacheIt);
733  }
734  }
735 
736  SeenVals.clear();
737  return Result;
738 }
739 
740 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
741  ObjectSizeOpts ObjSizeOptions;
742  ObjSizeOptions.RoundToAlign = RoundToAlign;
743 
744  ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, ObjSizeOptions);
745  SizeOffsetType Const = Visitor.compute(V);
746  if (Visitor.bothKnown(Const))
747  return std::make_pair(ConstantInt::get(Context, Const.first),
748  ConstantInt::get(Context, Const.second));
749 
750  V = V->stripPointerCasts();
751 
752  // Check cache.
753  CacheMapTy::iterator CacheIt = CacheMap.find(V);
754  if (CacheIt != CacheMap.end())
755  return CacheIt->second;
756 
757  // Always generate code immediately before the instruction being
758  // processed, so that the generated code dominates the same BBs.
759  BuilderTy::InsertPointGuard Guard(Builder);
760  if (Instruction *I = dyn_cast<Instruction>(V))
761  Builder.SetInsertPoint(I);
762 
763  // Now compute the size and offset.
764  SizeOffsetEvalType Result;
765 
766  // Record the pointers that were handled in this run, so that they can be
767  // cleaned later if something fails. We also use this set to break cycles that
768  // can occur in dead code.
769  if (!SeenVals.insert(V).second) {
770  Result = unknown();
771  } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
772  Result = visitGEPOperator(*GEP);
773  } else if (Instruction *I = dyn_cast<Instruction>(V)) {
774  Result = visit(*I);
775  } else if (isa<Argument>(V) ||
776  (isa<ConstantExpr>(V) &&
777  cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
778  isa<GlobalAlias>(V) ||
779  isa<GlobalVariable>(V)) {
780  // Ignore values where we cannot do more than ObjectSizeVisitor.
781  Result = unknown();
782  } else {
783  DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
784  << *V << '\n');
785  Result = unknown();
786  }
787 
788  // Don't reuse CacheIt since it may be invalid at this point.
789  CacheMap[V] = Result;
790  return Result;
791 }
792 
794  if (!I.getAllocatedType()->isSized())
795  return unknown();
796 
797  // must be a VLA
799  Value *ArraySize = I.getArraySize();
800  Value *Size = ConstantInt::get(ArraySize->getType(),
802  Size = Builder.CreateMul(Size, ArraySize);
803  return std::make_pair(Size, Zero);
804 }
805 
808  if (!FnData)
809  return unknown();
810 
811  // Handle strdup-like functions separately.
812  if (FnData->AllocTy == StrDupLike) {
813  // TODO
814  return unknown();
815  }
816 
817  Value *FirstArg = CS.getArgument(FnData->FstParam);
818  FirstArg = Builder.CreateZExt(FirstArg, IntTy);
819  if (FnData->SndParam < 0)
820  return std::make_pair(FirstArg, Zero);
821 
822  Value *SecondArg = CS.getArgument(FnData->SndParam);
823  SecondArg = Builder.CreateZExt(SecondArg, IntTy);
824  Value *Size = Builder.CreateMul(FirstArg, SecondArg);
825  return std::make_pair(Size, Zero);
826 
827  // TODO: handle more standard functions (+ wchar cousins):
828  // - strdup / strndup
829  // - strcpy / strncpy
830  // - strcat / strncat
831  // - memcpy / memmove
832  // - strcat / strncat
833  // - memset
834 }
835 
838  return unknown();
839 }
840 
843  return unknown();
844 }
845 
848  SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
849  if (!bothKnown(PtrData))
850  return unknown();
851 
852  Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
853  Offset = Builder.CreateAdd(PtrData.second, Offset);
854  return std::make_pair(PtrData.first, Offset);
855 }
856 
858  // clueless
859  return unknown();
860 }
861 
863  return unknown();
864 }
865 
867  // Create 2 PHIs: one for size and another for offset.
868  PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
869  PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
870 
871  // Insert right away in the cache to handle recursive PHIs.
872  CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
873 
874  // Compute offset/size for each PHI incoming pointer.
875  for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
877  SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
878 
879  if (!bothKnown(EdgeData)) {
880  OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
881  OffsetPHI->eraseFromParent();
882  SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
883  SizePHI->eraseFromParent();
884  return unknown();
885  }
886  SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
887  OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
888  }
889 
890  Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
891  if ((Tmp = SizePHI->hasConstantValue())) {
892  Size = Tmp;
893  SizePHI->replaceAllUsesWith(Size);
894  SizePHI->eraseFromParent();
895  }
896  if ((Tmp = OffsetPHI->hasConstantValue())) {
897  Offset = Tmp;
898  OffsetPHI->replaceAllUsesWith(Offset);
899  OffsetPHI->eraseFromParent();
900  }
901  return std::make_pair(Size, Offset);
902 }
903 
905  SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
906  SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
907 
908  if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
909  return unknown();
910  if (TrueSide == FalseSide)
911  return TrueSide;
912 
913  Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
914  FalseSide.first);
915  Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
916  FalseSide.second);
917  return std::make_pair(Size, Offset);
918 }
919 
921  DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
922  return unknown();
923 }
bool getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Compute the size of the object pointed by Ptr.
Value * EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
Definition: Local.h:201
uint64_t CallInst * C
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:69
unsigned getAlignment() const
Definition: GlobalObject.h:59
bool isAllocationFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates or reallocates memory (eith...
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:243
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
static const std::pair< LibFunc, AllocFnsTy > AllocationFnData[]
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
This instruction extracts a struct member or array element value from an aggregate value...
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1542
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
LLVMContext & Context
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:135
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:262
unsigned NumParams
const CallInst * extractCallocCall(const Value *I, const TargetLibraryInfo *TLI)
extractCallocCall - Returns the corresponding CallInst if the instruction is a calloc call...
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:562
Attribute
Attributes.
Definition: Dwarf.h:105
bool hasByValOrInAllocaAttr() const
Return true if this argument has the byval attribute or inalloca attribute.
Definition: Function.cpp:106
bool NullIsUnknownSize
If this is true, null pointers in address space 0 will be treated as though they can&#39;t be evaluated...
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1183
This class represents a function call, abstracting a target machine&#39;s calling convention.
This file contains the declarations for metadata subclasses.
static Optional< AllocFnsTy > getAllocationDataForFunction(const Function *Callee, AllocType AllocTy, const TargetLibraryInfo *TLI)
Returns the allocation data for the given value if it&#39;s either a call to a known allocation function...
const Value * getTrueValue() const
bool RoundToAlign
Whether to round the result up to the alignment of allocas, byval arguments, and global variables...
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:697
SizeOffsetType visitAllocaInst(AllocaInst &I)
bool isInterposable() const
Return true if this global&#39;s definition can be substituted with an arbitrary definition at link time...
Definition: GlobalValue.h:400
bool sgt(const APInt &RHS) const
Signed greather than comparison.
Definition: APInt.h:1253
AllocType
STATISTIC(NumFunctions, "Total number of functions")
The two locations do not alias at all.
Definition: AliasAnalysis.h:79
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:677
An instruction for reading from memory.
Definition: Instructions.h:164
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:883
SizeOffsetType visitArgument(Argument &A)
Hexagon Common GEP
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1488
bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const
Accumulate the constant address offset of this GEP if possible.
Definition: Operator.cpp:35
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:130
const CallInst * isFreeCall(const Value *I, const TargetLibraryInfo *TLI)
isFreeCall - Returns non-null if the value is a call to the builtin free()
This class represents the LLVM &#39;select&#39; instruction.
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:109
SizeOffsetEvalType visitGEPOperator(GEPOperator &GEP)
SizeOffsetType visitExtractValueInst(ExtractValueInst &I)
SizeOffsetType visitGEPOperator(GEPOperator &GEP)
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
Definition: DataLayout.cpp:614
&#39;undef&#39; values are things that do not have specified contents.
Definition: Constants.h:1247
static Optional< AllocFnsTy > getAllocationSize(const Value *V, const TargetLibraryInfo *TLI)
Class to represent struct types.
Definition: DerivedTypes.h:201
APInt zextOrSelf(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:899
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
SizeOffsetEvalType visitCallSite(CallSite CS)
SizeOffsetType visitIntToPtrInst(IntToPtrInst &)
InstrTy * getInstruction() const
Definition: CallSite.h:89
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:889
ObjectSizeOffsetEvaluator(const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context, bool RoundToAlign=false)
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1512
bool isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a function that returns a NoAlias pointer (including malloc/c...
Same as Min, except we pick the maximum size of all of the branches.
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:862
Class to represent function types.
Definition: DerivedTypes.h:103
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
Evaluate all branches of an unknown condition.
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Definition: CallSite.h:425
bool has(LibFunc F) const
Tests whether a library function is available.
This class represents a no-op cast from one type to another.
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:138
TargetFolder - Create constants with target dependent folding.
Definition: TargetFolder.h:32
std::pair< APInt, APInt > SizeOffsetType
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:428
std::pair< unsigned, Optional< unsigned > > getAllocSizeArgs() const
Returns the argument numbers for the allocsize attribute (or pair(0, 0) if not known).
Definition: Attributes.cpp:237
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1383
uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return &#39;len+1&#39;...
SizeOffsetType visitInstruction(Instruction &I)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:128
Class to represent pointers.
Definition: DerivedTypes.h:467
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:131
Value * getMallocArraySize(CallInst *CI, const DataLayout &DL, const TargetLibraryInfo *TLI, bool LookThroughSExt=false)
getMallocArraySize - Returns the array size of a malloc call.
SizeOffsetType visitGlobalVariable(GlobalVariable &GV)
bool isVoidTy() const
Return true if this is &#39;void&#39;.
Definition: Type.h:141
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:702
#define P(N)
bool erase(const KeyT &Val)
Definition: DenseMap.h:247
SizeOffsetEvalType visitSelectInst(SelectInst &I)
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:200
ConstantInt * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to .objectsize into an integer value of the given Type.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
const CallInst * extractMallocCall(const Value *I, const TargetLibraryInfo *TLI)
extractMallocCall - Returns the corresponding CallInst if the instruction is a malloc call...
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.h:1689
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:139
#define A
Definition: LargeTest.cpp:12
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:372
static Value * computeArraySize(const CallInst *CI, const DataLayout &DL, const TargetLibraryInfo *TLI, bool LookThroughSExt=false)
static APInt getSizeWithOverflow(const SizeOffsetType &Data)
Value * getPointerOperand()
Definition: Operator.h:420
static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:495
static Optional< AllocFnsTy > getAllocationData(const Value *V, AllocType AllocTy, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
This class represents a cast from an integer to a pointer.
const Value * getCondition() const
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:194
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1320
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:527
SizeOffsetType visitCallSite(CallSite CS)
const Value * getArraySize() const
Get the number of elements allocated.
Definition: Instructions.h:93
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:220
PointerType * getMallocType(const CallInst *CI, const TargetLibraryInfo *TLI)
getMallocType - Returns the PointerType resulting from the malloc call.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:933
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:102
SizeOffsetType visitSelectInst(SelectInst &I)
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:51
SizeOffsetType visitExtractElementInst(ExtractElementInst &I)
SizeOffsetType visitGlobalAlias(GlobalAlias &GA)
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:1654
SizeOffsetEvalType visitInstruction(Instruction &I)
Value * hasConstantValue() const
If the specified PHI node always merges together the same value, return the value, otherwise return null.
unsigned getNumOperands() const
Definition: User.h:176
Mode EvalMode
How we want to evaluate this object&#39;s size.
#define E
Definition: LargeTest.cpp:27
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
ValTy * getArgument(unsigned ArgNo) const
Definition: CallSite.h:183
Evaluate the size and offset of an object pointed to by a Value* statically.
unsigned getParamAlignment() const
If this is a byval or inalloca argument, return its alignment.
Definition: Function.cpp:113
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
SizeOffsetType visitPHINode(PHINode &)
A constant pointer value that points to null.
Definition: Constants.h:530
Type * getReturnType() const
Definition: DerivedTypes.h:124
uint64_t getSizeInBytes() const
Definition: DataLayout.h:501
SizeOffsetType visitUndefValue(UndefValue &)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:560
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static const Function * getCalledFunction(const Value *V, bool LookThroughBitCast, bool &IsNoBuiltin)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
SizeOffsetType compute(Value *V)
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:137
Class for arbitrary precision integers.
Definition: APInt.h:69
std::pair< Value *, Value * > SizeOffsetEvalType
SizeOffsetEvalType visitIntToPtrInst(IntToPtrInst &)
Type * getMallocAllocatedType(const CallInst *CI, const TargetLibraryInfo *TLI)
getMallocAllocatedType - Returns the Type allocated by malloc call.
SizeOffsetEvalType visitPHINode(PHINode &PHI)
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
bool isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates uninitialized memory (such ...
const Value * getFalseValue() const
user_iterator_impl< const User > const_user_iterator
Definition: Value.h:365
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
Fail to evaluate an unknown condition.
SizeOffsetEvalType compute(Value *V)
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:405
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
Definition: APInt.h:1234
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:529
ObjectSizeOffsetVisitor(const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context, ObjectSizeOpts Options={})
SizeOffsetEvalType visitLoadInst(LoadInst &I)
bool isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates memory similar to malloc or...
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:218
Establish a view to a call site for examination.
Definition: CallSite.h:687
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
bool isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates zero-filled memory (such as...
#define I(x, y, z)
Definition: MD5.cpp:58
PointerType * getType() const
Specialize the getType() method to always return an PointerType, which reduces the amount of casting ...
Definition: Constants.h:546
bool isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
iterator end()
Definition: DenseMap.h:73
bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple, bool LookThroughSExt=false, unsigned Depth=0)
This function computes the integer multiple of Base that equals V.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
This instruction extracts a single (scalar) element from a VectorType value.
bool anyKnown(SizeOffsetEvalType SizeOffset)
APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1915
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:200
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it&#39;s an indirect...
Definition: CallSite.h:104
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Definition: Value.h:371
static bool bothKnown(const SizeOffsetType &SizeOffset)
LLVM Value Representation.
Definition: Value.h:73
SizeOffsetEvalType visitExtractElementInst(ExtractElementInst &I)
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:262
AllocType AllocTy
#define DEBUG(X)
Definition: Debug.h:118
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
Various options to control the behavior of getObjectSize.
static APInt getNullValue(unsigned numBits)
Get the &#39;0&#39; value.
Definition: APInt.h:562
int * Ptr
auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:846
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:385
SizeOffsetType visitLoadInst(LoadInst &I)
SizeOffsetEvalType visitAllocaInst(AllocaInst &I)
bool bothKnown(SizeOffsetEvalType SizeOffset)
SizeOffsetType visitConstantPointerNull(ConstantPointerNull &)
SizeOffsetEvalType visitExtractValueInst(ExtractValueInst &I)
Type * getElementType() const
Definition: DerivedTypes.h:486
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:260
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
an instruction to allocate memory on the stack
Definition: Instructions.h:60
user_iterator user_end()
Definition: Value.h:379
const Constant * getAliasee() const
Definition: GlobalAlias.h:78