LLVM 24.0.0git
Evaluator.cpp
Go to the documentation of this file.
1//===- Evaluator.cpp - LLVM IR evaluator ----------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Function evaluator for LLVM IR.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/STLExtras.h"
19#include "llvm/IR/BasicBlock.h"
20#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/Function.h"
25#include "llvm/IR/GlobalAlias.h"
26#include "llvm/IR/GlobalValue.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
32#include "llvm/IR/Type.h"
33#include "llvm/IR/User.h"
34#include "llvm/IR/Value.h"
36#include "llvm/Support/Debug.h"
38
39#define DEBUG_TYPE "evaluator"
40
41using namespace llvm;
42
43static inline bool
45 SmallPtrSetImpl<Constant *> &SimpleConstants,
46 const DataLayout &DL);
47
48/// Return true if the specified constant can be handled by the code generator.
49/// We don't want to generate something like:
50/// void *X = &X/42;
51/// because the code generator doesn't have a relocation that can handle that.
52///
53/// This function should be called if C was not found (but just got inserted)
54/// in SimpleConstants to avoid having to rescan the same constants all the
55/// time.
56static bool
58 SmallPtrSetImpl<Constant *> &SimpleConstants,
59 const DataLayout &DL) {
60 // Simple global addresses are supported, do not allow dllimport or
61 // thread-local globals.
62 if (auto *GV = dyn_cast<GlobalValue>(C))
63 return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal();
64
65 // Simple integer, undef, constant aggregate zero, etc are all supported.
66 if (C->getNumOperands() == 0 || isa<BlockAddress>(C))
67 return true;
68
69 // Aggregate values are safe if all their elements are.
71 for (Value *Op : C->operands())
72 if (!isSimpleEnoughValueToCommit(cast<Constant>(Op), SimpleConstants, DL))
73 return false;
74 return true;
75 }
76
77 // We don't know exactly what relocations are allowed in constant expressions,
78 // so we allow &global+constantoffset, which is safe and uniformly supported
79 // across targets.
81 if (!CE)
82 return false;
83 switch (CE->getOpcode()) {
84 case Instruction::BitCast:
85 // Bitcast is fine if the casted value is fine.
86 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
87
88 case Instruction::IntToPtr:
89 case Instruction::PtrToInt:
90 // int <=> ptr is fine if the int type is the same size as the
91 // pointer type.
92 if (DL.getTypeSizeInBits(CE->getType()) !=
93 DL.getTypeSizeInBits(CE->getOperand(0)->getType()))
94 return false;
95 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
96
97 // GEP is fine if it is simple + constant offset.
98 case Instruction::GetElementPtr:
99 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
100 if (!isa<ConstantInt>(CE->getOperand(i)))
101 return false;
102 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
103
104 case Instruction::Add:
105 // We allow simple+cst.
106 if (!isa<ConstantInt>(CE->getOperand(1)))
107 return false;
108 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
109 }
110 return false;
111}
112
113static inline bool
115 SmallPtrSetImpl<Constant *> &SimpleConstants,
116 const DataLayout &DL) {
117 // If we already checked this constant, we win.
118 if (!SimpleConstants.insert(C).second)
119 return true;
120 // Check the constant.
121 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL);
122}
123
124void Evaluator::MutableValue::clear() {
125 if (auto *Agg = dyn_cast_if_present<MutableAggregate *>(Val))
126 delete Agg;
127 Val = nullptr;
128}
129
130Constant *Evaluator::MutableValue::read(Type *Ty, APInt Offset,
131 const DataLayout &DL) const {
132 TypeSize TySize = DL.getTypeStoreSize(Ty);
133 const MutableValue *V = this;
134 while (const auto *Agg = dyn_cast_if_present<MutableAggregate *>(V->Val)) {
135 Type *AggTy = Agg->Ty;
136 std::optional<APInt> Index = DL.getGEPIndexForOffset(AggTy, Offset);
137 if (!Index || Index->uge(Agg->Elements.size()) ||
138 !TypeSize::isKnownLE(TySize, DL.getTypeStoreSize(AggTy)))
139 return nullptr;
140
141 V = &Agg->Elements[Index->getZExtValue()];
142 }
143
144 return ConstantFoldLoadFromConst(cast<Constant *>(V->Val), Ty, Offset, DL);
145}
146
147bool Evaluator::MutableValue::makeMutable() {
149 Type *Ty = C->getType();
150 unsigned NumElements;
151 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
152 NumElements = VT->getNumElements();
153 } else if (auto *AT = dyn_cast<ArrayType>(Ty))
154 NumElements = AT->getNumElements();
155 else if (auto *ST = dyn_cast<StructType>(Ty))
156 NumElements = ST->getNumElements();
157 else
158 return false;
159
160 MutableAggregate *MA = new MutableAggregate(Ty);
161 MA->Elements.reserve(NumElements);
162 for (unsigned I = 0; I < NumElements; ++I)
163 MA->Elements.push_back(C->getAggregateElement(I));
164 Val = MA;
165 return true;
166}
167
168bool Evaluator::MutableValue::write(Constant *V, APInt Offset,
169 const DataLayout &DL) {
170 Type *Ty = V->getType();
171 TypeSize TySize = DL.getTypeStoreSize(Ty);
172 MutableValue *MV = this;
173 while (Offset != 0 ||
174 !CastInst::isBitOrNoopPointerCastable(Ty, MV->getType(), DL)) {
175 if (isa<Constant *>(MV->Val) && !MV->makeMutable())
176 return false;
177
178 MutableAggregate *Agg = cast<MutableAggregate *>(MV->Val);
179 Type *AggTy = Agg->Ty;
180 std::optional<APInt> Index = DL.getGEPIndexForOffset(AggTy, Offset);
181 if (!Index || Index->uge(Agg->Elements.size()) ||
182 !TypeSize::isKnownLE(TySize, DL.getTypeStoreSize(AggTy)))
183 return false;
184
185 MV = &Agg->Elements[Index->getZExtValue()];
186 }
187
188 Type *MVType = MV->getType();
189 MV->clear();
190 if (Ty->isIntegerTy() && MVType->isPointerTy())
191 MV->Val = ConstantExpr::getIntToPtr(V, MVType);
192 else if (Ty->isPointerTy() && MVType->isIntegerTy())
193 MV->Val = ConstantExpr::getPtrToInt(V, MVType);
194 else if (Ty != MVType)
195 MV->Val = ConstantExpr::getBitCast(V, MVType);
196 else
197 MV->Val = V;
198 return true;
199}
200
201Constant *Evaluator::MutableAggregate::toConstant() const {
203 for (const MutableValue &MV : Elements)
204 Consts.push_back(MV.toConstant());
205
206 if (auto *ST = dyn_cast<StructType>(Ty))
207 return ConstantStruct::get(ST, Consts);
208 if (auto *AT = dyn_cast<ArrayType>(Ty))
209 return ConstantArray::get(AT, Consts);
210 assert(isa<FixedVectorType>(Ty) && "Must be vector");
211 return ConstantVector::get(Consts);
212}
213
214/// Return the value that would be computed by a load from P after the stores
215/// reflected by 'memory' have been performed. If we can't decide, return null.
216Constant *Evaluator::ComputeLoadResult(Constant *P, Type *Ty) {
217 APInt Offset(DL.getIndexTypeSizeInBits(P->getType()), 0);
218 P = cast<Constant>(P->stripAndAccumulateConstantOffsets(
219 DL, Offset, /* AllowNonInbounds */ true));
220 Offset = Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(P->getType()));
221 if (auto *GV = dyn_cast<GlobalVariable>(P))
222 return ComputeLoadResult(GV, Ty, Offset);
223 return nullptr;
224}
225
226Constant *Evaluator::ComputeLoadResult(GlobalVariable *GV, Type *Ty,
227 const APInt &Offset) {
228 auto It = MutatedMemory.find(GV);
229 if (It != MutatedMemory.end())
230 return It->second.read(Ty, Offset, DL);
231
232 if (!GV->hasDefinitiveInitializer())
233 return nullptr;
234 return ConstantFoldLoadFromConst(GV->getInitializer(), Ty, Offset, DL);
235}
236
238 if (auto *Fn = dyn_cast<Function>(C))
239 return Fn;
240
241 if (auto *Alias = dyn_cast<GlobalAlias>(C))
242 if (auto *Fn = dyn_cast<Function>(Alias->getAliasee()))
243 return Fn;
244 return nullptr;
245}
246
247Function *
248Evaluator::getCalleeWithFormalArgs(CallBase &CB,
249 SmallVectorImpl<Constant *> &Formals) {
250 auto *V = CB.getCalledOperand()->stripPointerCasts();
251 if (auto *Fn = getFunction(getVal(V)))
252 return getFormalParams(CB, Fn, Formals) ? Fn : nullptr;
253 return nullptr;
254}
255
256bool Evaluator::getFormalParams(CallBase &CB, Function *F,
257 SmallVectorImpl<Constant *> &Formals) {
258 auto *FTy = F->getFunctionType();
259 if (FTy != CB.getFunctionType()) {
260 LLVM_DEBUG(dbgs() << "Signature mismatch.\n");
261 return false;
262 }
263
264 for (unsigned I = 0, E = CB.arg_size(); I != E; ++I) {
265 Constant *Arg = getVal(CB.getArgOperand(I));
266 if (CB.isByValArgument(I)) {
267 constexpr uint64_t MaxByValCopySize = 256;
268 std::optional<Align> ParamAlign = CB.getParamAlign(I);
269 Type *ByValTy = CB.getParamByValType(I);
270 uint64_t Size = DL.getTypeAllocSize(ByValTy);
271 APInt Base(DL.getIndexTypeSizeInBits(Arg->getType()), 0);
272 auto *GV = dyn_cast<GlobalVariable>(
274 if (!GV || !ParamAlign || Size > MaxByValCopySize) {
275 LLVM_DEBUG(dbgs() << "Cannot copy the byval argument.\n");
276 return false;
277 }
278 Type *I8Ty = Type::getInt8Ty(CB.getContext());
280 for (uint64_t Off = 0; Off != Size; ++Off) {
281 Constant *Byte =
282 ComputeLoadResult(GV, I8Ty, Base + APInt(Base.getBitWidth(), Off));
283 if (!Byte) {
284 LLVM_DEBUG(dbgs() << "Cannot read the byval argument.\n");
285 return false;
286 }
287 Bytes.push_back(Byte);
288 }
289 ArrayType *CopyTy = ArrayType::get(I8Ty, Size);
290 auto NewGV = std::make_unique<GlobalVariable>(
291 CopyTy, false, GlobalValue::InternalLinkage,
292 ConstantArray::get(CopyTy, Bytes), "byval.copy",
295 NewGV->setAlignment(*ParamAlign);
296 AllocaTmps.push_back(std::move(NewGV));
297 Arg = AllocaTmps.back().get();
298 }
299 Formals.push_back(Arg);
300 }
301 return true;
302}
303
304/// Evaluate all instructions in block BB, returning true if successful, false
305/// if we can't evaluate it. NewBB returns the next BB that control flows into,
306/// or null upon return. StrippedPointerCastsForAliasAnalysis is set to true if
307/// we looked through pointer casts to evaluate something.
308bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
309 TargetLibraryInfo *TLI, BasicBlock *&NextBB,
310 bool &StrippedPointerCastsForAliasAnalysis) {
311 // This is the main evaluation loop.
312 while (true) {
313 Constant *InstResult = nullptr;
314
315 LLVM_DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
316
317 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
318 if (SI->isVolatile()) {
319 LLVM_DEBUG(dbgs() << "Store is volatile! Can not evaluate.\n");
320 return false; // no volatile accesses.
321 }
322 Constant *Ptr = getVal(SI->getOperand(1));
323 Constant *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI);
324 if (Ptr != FoldedPtr) {
325 LLVM_DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
326 Ptr = FoldedPtr;
327 LLVM_DEBUG(dbgs() << "; To: " << *Ptr << "\n");
328 }
329
330 APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
332 DL, Offset, /* AllowNonInbounds */ true));
333 Offset = Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(Ptr->getType()));
334 auto *GV = dyn_cast<GlobalVariable>(Ptr);
335 if (!GV || !GV->hasUniqueInitializer() || GV->hasSection()) {
336 // hasUniqueInitializer() ensures that if we modify the initializer,
337 // the modified initializer will be used.
338 //
339 // We can't modify global variables with an explicit section because
340 // it might not be legal to emit the resulting initializer (for
341 // example, emitting a non-zero value into a BSS section).
342 LLVM_DEBUG(dbgs() << "Store is not to global with unique initializer: "
343 << *Ptr << "\n");
344 return false;
345 }
346
347 // If this might be too difficult for the backend to handle (e.g. the addr
348 // of one global variable divided by another) then we can't commit it.
349 Constant *Val = getVal(SI->getOperand(0));
350 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
351 LLVM_DEBUG(dbgs() << "Store value is too complex to evaluate store. "
352 << *Val << "\n");
353 return false;
354 }
355
356 auto Res = MutatedMemory.try_emplace(GV, GV->getInitializer());
357 if (!Res.first->second.write(Val, Offset, DL))
358 return false;
359 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
360 if (LI->isVolatile()) {
362 dbgs() << "Found a Load! Volatile load, can not evaluate.\n");
363 return false; // no volatile accesses.
364 }
365
366 Constant *Ptr = getVal(LI->getOperand(0));
367 Constant *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI);
368 if (Ptr != FoldedPtr) {
369 Ptr = FoldedPtr;
370 LLVM_DEBUG(dbgs() << "Found a constant pointer expression, constant "
371 "folding: "
372 << *Ptr << "\n");
373 }
374 InstResult = ComputeLoadResult(Ptr, LI->getType());
375 if (!InstResult) {
377 dbgs() << "Failed to compute load result. Can not evaluate load."
378 "\n");
379 return false; // Could not evaluate load.
380 }
381
382 LLVM_DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
383 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
384 if (AI->isArrayAllocation()) {
385 LLVM_DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
386 return false; // Cannot handle array allocs.
387 }
388 Type *Ty = AI->getAllocatedType();
389 AllocaTmps.push_back(std::make_unique<GlobalVariable>(
391 AI->getName(), /*TLMode=*/GlobalValue::NotThreadLocal,
392 AI->getType()->getPointerAddressSpace()));
393 InstResult = AllocaTmps.back().get();
394 LLVM_DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
395 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
396 CallBase &CB = *cast<CallBase>(&*CurInst);
397
398 // Cannot handle inline asm.
399 if (CB.isInlineAsm()) {
400 LLVM_DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
401 return false;
402 }
403
404 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CB)) {
405 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
406 if (MSI->isVolatile()) {
407 LLVM_DEBUG(dbgs() << "Can not optimize a volatile memset "
408 << "intrinsic.\n");
409 return false;
410 }
411
412 auto *LenC = dyn_cast<ConstantInt>(getVal(MSI->getLength()));
413 if (!LenC) {
414 LLVM_DEBUG(dbgs() << "Memset with unknown length.\n");
415 return false;
416 }
417
418 Constant *Ptr = getVal(MSI->getDest());
419 APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
421 DL, Offset, /* AllowNonInbounds */ true));
422 auto *GV = dyn_cast<GlobalVariable>(Ptr);
423 if (!GV) {
424 LLVM_DEBUG(dbgs() << "Memset with unknown base.\n");
425 return false;
426 }
427
428 Constant *Val = getVal(MSI->getValue());
429 // Avoid the byte-per-byte scan if we're memseting a zeroinitializer
430 // to zero.
431 if (!Val->isNullValue() || MutatedMemory.contains(GV) ||
433 !GV->getInitializer()->isNullValue()) {
434 APInt Len = LenC->getValue();
435 if (Len.ugt(64 * 1024)) {
436 LLVM_DEBUG(dbgs() << "Not evaluating large memset of size "
437 << Len << "\n");
438 return false;
439 }
440
441 while (Len != 0) {
442 Constant *DestVal = ComputeLoadResult(GV, Val->getType(), Offset);
443 if (DestVal != Val) {
444 LLVM_DEBUG(dbgs() << "Memset is not a no-op at offset "
445 << Offset << " of " << *GV << ".\n");
446 return false;
447 }
448 ++Offset;
449 --Len;
450 }
451 }
452
453 LLVM_DEBUG(dbgs() << "Ignoring no-op memset.\n");
454 ++CurInst;
455 continue;
456 }
457
458 if (II->isLifetimeStartOrEnd()) {
459 LLVM_DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
460 ++CurInst;
461 continue;
462 }
463
464 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
465 // We don't insert an entry into Values, as it doesn't have a
466 // meaningful return value.
467 if (!II->use_empty()) {
469 << "Found unused invariant_start. Can't evaluate.\n");
470 return false;
471 }
472 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
473 Value *PtrArg = getVal(II->getArgOperand(1));
474 Value *Ptr = PtrArg->stripPointerCasts();
475 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
476 uint64_t MinGVSize = GV->getGlobalSize(DL);
477 if (!Size->isMinusOne() &&
478 Size->getValue().getLimitedValue() >= MinGVSize) {
479 Invariants.insert(GV);
480 LLVM_DEBUG(dbgs() << "Found a global var that is an invariant: "
481 << *GV << "\n");
482 } else {
484 << "Found a global var, but can not treat it as an "
485 "invariant.\n");
486 }
487 }
488 // Continue even if we do nothing.
489 ++CurInst;
490 continue;
491 } else if (II->getIntrinsicID() == Intrinsic::assume) {
492 LLVM_DEBUG(dbgs() << "Skipping assume intrinsic.\n");
493 ++CurInst;
494 continue;
495 } else if (II->getIntrinsicID() == Intrinsic::sideeffect) {
496 LLVM_DEBUG(dbgs() << "Skipping sideeffect intrinsic.\n");
497 ++CurInst;
498 continue;
499 } else if (II->getIntrinsicID() == Intrinsic::pseudoprobe) {
500 LLVM_DEBUG(dbgs() << "Skipping pseudoprobe intrinsic.\n");
501 ++CurInst;
502 continue;
503 } else {
504 Value *Stripped = CurInst->stripPointerCastsForAliasAnalysis();
505 // Only attempt to getVal() if we've actually managed to strip
506 // anything away, or else we'll call getVal() on the current
507 // instruction.
508 if (Stripped != &*CurInst) {
509 InstResult = getVal(Stripped);
510 }
511 if (InstResult) {
513 << "Stripped pointer casts for alias analysis for "
514 "intrinsic call.\n");
515 StrippedPointerCastsForAliasAnalysis = true;
516 InstResult = ConstantExpr::getBitCast(InstResult, II->getType());
517 } else {
518 LLVM_DEBUG(dbgs() << "Unknown intrinsic. Cannot evaluate.\n");
519 return false;
520 }
521 }
522 }
523
524 if (!InstResult) {
525 // Resolve function pointers.
527 Function *Callee = getCalleeWithFormalArgs(CB, Formals);
528 if (!Callee || Callee->isInterposable()) {
529 LLVM_DEBUG(dbgs() << "Can not resolve function pointer.\n");
530 return false; // Cannot resolve.
531 }
532
533 if (Callee->isDeclaration()) {
534 // If this is a function we can constant fold, do it.
535 if (Constant *C = ConstantFoldCall(&CB, Callee, Formals, TLI)) {
536 InstResult = C;
537 LLVM_DEBUG(dbgs() << "Constant folded function call. Result: "
538 << *InstResult << "\n");
539 } else {
540 LLVM_DEBUG(dbgs() << "Can not constant fold function call.\n");
541 return false;
542 }
543 } else {
544 if (Callee->getFunctionType()->isVarArg()) {
546 << "Can not constant fold vararg function call.\n");
547 return false;
548 }
549
550 Constant *RetVal = nullptr;
551 // Execute the call, if successful, use the return value.
552 ValueStack.emplace_back();
553 if (!EvaluateFunction(Callee, RetVal, Formals)) {
554 LLVM_DEBUG(dbgs() << "Failed to evaluate function.\n");
555 return false;
556 }
557 ValueStack.pop_back();
558 InstResult = RetVal;
559 if (InstResult) {
560 LLVM_DEBUG(dbgs() << "Successfully evaluated function. Result: "
561 << *InstResult << "\n\n");
562 } else {
564 << "Successfully evaluated function. Result: 0\n\n");
565 }
566 }
567 }
568 } else if (CurInst->isTerminator()) {
569 LLVM_DEBUG(dbgs() << "Found a terminator instruction.\n");
570
571 if (UncondBrInst *BI = dyn_cast<UncondBrInst>(CurInst)) {
572 NextBB = BI->getSuccessor(0);
573 } else if (CondBrInst *BI = dyn_cast<CondBrInst>(CurInst)) {
574 ConstantInt *Cond = dyn_cast<ConstantInt>(getVal(BI->getCondition()));
575 if (!Cond)
576 return false; // Cannot determine.
577 NextBB = BI->getSuccessor(!Cond->getZExtValue());
578 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
579 ConstantInt *Val =
580 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
581 if (!Val) return false; // Cannot determine.
582 NextBB = SI->findCaseValue(Val)->getCaseSuccessor();
583 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
584 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
585 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
586 NextBB = BA->getBasicBlock();
587 else
588 return false; // Cannot determine.
589 } else if (isa<ReturnInst>(CurInst)) {
590 NextBB = nullptr;
591 } else {
592 // invoke, unwind, resume, unreachable.
593 LLVM_DEBUG(dbgs() << "Can not handle terminator.");
594 return false; // Cannot handle this terminator.
595 }
596
597 // We succeeded at evaluating this block!
598 LLVM_DEBUG(dbgs() << "Successfully evaluated block.\n");
599 return true;
600 } else {
602 for (Value *Op : CurInst->operands())
603 Ops.push_back(getVal(Op));
604 InstResult = ConstantFoldInstOperands(&*CurInst, Ops, DL, TLI);
605 if (!InstResult) {
606 LLVM_DEBUG(dbgs() << "Cannot fold instruction: " << *CurInst << "\n");
607 return false;
608 }
609 LLVM_DEBUG(dbgs() << "Folded instruction " << *CurInst << " to "
610 << *InstResult << "\n");
611 }
612
613 if (!CurInst->use_empty()) {
614 InstResult = ConstantFoldConstant(InstResult, DL, TLI);
615 setVal(&*CurInst, InstResult);
616 }
617
618 // If we just processed an invoke, we finished evaluating the block.
619 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
620 NextBB = II->getNormalDest();
621 LLVM_DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
622 return true;
623 }
624
625 // Advance program counter.
626 ++CurInst;
627 }
628}
629
630/// Evaluate a call to function F, returning true if successful, false if we
631/// can't evaluate it. ActualArgs contains the formal arguments for the
632/// function.
634 Function *F, Constant *&RetVal,
635 const SmallVectorImpl<Constant *> &ActualArgs) {
636 assert(ActualArgs.size() == F->arg_size() && "wrong number of arguments");
637
638 // Check to see if this function is already executing (recursion). If so,
639 // bail out. TODO: we might want to accept limited recursion.
640 if (is_contained(CallStack, F))
641 return false;
642
643 CallStack.push_back(F);
644
645 // Initialize arguments to the incoming values specified.
646 for (const auto &[ArgNo, Arg] : llvm::enumerate(F->args()))
647 setVal(&Arg, ActualArgs[ArgNo]);
648
649 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
650 // we can only evaluate any one basic block at most once. This set keeps
651 // track of what we have executed so we can detect recursive cases etc.
652 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
653
654 // CurBB - The current basic block we're evaluating.
655 BasicBlock *CurBB = &F->front();
656
657 BasicBlock::iterator CurInst = CurBB->begin();
658
659 TargetLibraryInfo *TLI = GetTLI ? &GetTLI(*F) : nullptr;
660 while (true) {
661 BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
662 LLVM_DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
663
664 bool StrippedPointerCastsForAliasAnalysis = false;
665
666 if (!EvaluateBlock(CurInst, TLI, NextBB,
667 StrippedPointerCastsForAliasAnalysis))
668 return false;
669
670 if (!NextBB) {
671 // Successfully running until there's no next block means that we found
672 // the return. Fill it the return value and pop the call stack.
674 if (RI->getNumOperands()) {
675 // The Evaluator can look through pointer casts as long as alias
676 // analysis holds because it's just a simple interpreter and doesn't
677 // skip memory accesses due to invariant group metadata, but we can't
678 // let users of Evaluator use a value that's been gleaned looking
679 // through stripping pointer casts.
680 if (StrippedPointerCastsForAliasAnalysis &&
681 !RI->getReturnValue()->getType()->isVoidTy()) {
682 return false;
683 }
684 RetVal = getVal(RI->getOperand(0));
685 }
686 CallStack.pop_back();
687 return true;
688 }
689
690 // Okay, we succeeded in evaluating this control flow. See if we have
691 // executed the new block before. If so, we have a looping function,
692 // which we cannot evaluate in reasonable time.
693 if (!ExecutedBlocks.insert(NextBB).second)
694 return false; // looped!
695
696 // Okay, we have never been in this block before. Check to see if there
697 // are any PHI nodes. If so, evaluate them with information about where
698 // we came from.
699 PHINode *PN = nullptr;
700 for (CurInst = NextBB->begin();
701 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
702 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
703
704 // Advance to the next block.
705 CurBB = NextBB;
706 }
707}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
static bool isSimpleEnoughValueToCommitHelper(Constant *C, SmallPtrSetImpl< Constant * > &SimpleConstants, const DataLayout &DL)
Return true if the specified constant can be handled by the code generator.
Definition Evaluator.cpp:57
static bool isSimpleEnoughValueToCommit(Constant *C, SmallPtrSetImpl< Constant * > &SimpleConstants, const DataLayout &DL)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define P(N)
SmallVector< MachineOperand, 4 > Cond
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
bool isInlineAsm() const
Check if this call is an inline asm statement.
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
MaybeAlign getParamAlign(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
Type * getParamByValType(unsigned ArgNo) const
Extract the byval type for a call or parameter.
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
unsigned arg_size() const
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
const Constant * stripPointerCasts() const
Definition Constant.h:243
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI bool EvaluateFunction(Function *F, Constant *&RetVal, const SmallVectorImpl< Constant * > &ActualArgs)
Evaluate a call to function F, returning true if successful, false if we can't evaluate it.
bool hasSection() const
Check if this global has a custom object file section.
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
bool hasUniqueInitializer() const
hasUniqueInitializer - Whether the global variable has an initializer, and any changes made to the in...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
Return a value (possibly void), from a function.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
Provides information about what library functions are available for the current target.
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:231
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
LLVM_ABI Constant * ConstantFoldCall(const CallBase *Call, Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.