[PATCH] D75600: Add nullptr check to isLandingPad

Lukas Diekmann via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Wed Mar 4 03:59:04 PST 2020


ptersilie created this revision.
ptersilie added a reviewer: lebedev.ri.
Herald added subscribers: llvm-commits, hiraditya.
Herald added a project: LLVM.

Calling `isLandingPad` on an empty `BasicBlock` can lead to undefined behaviour, e.g. see the following program:

  int main(void)
  {
      // Start with a LLVM context.
      LLVMContext TheContext;
  
      // Make a module.
      Module *TheModule = new Module("mymod", TheContext);
  
      // Make a function
      std::vector<Type*> NoArgs = {};
      Type *u32 = Type::getInt32Ty(TheContext);
      FunctionType *FT = FunctionType::get(u32, NoArgs, false);
      Function *F = Function::Create(FT, Function::ExternalLinkage, "main", TheModule);
  
      // Make an empty block
      IRBuilder<> Builder(TheContext);
      BasicBlock *BB = BasicBlock::Create(TheContext, "entry", F);
      Builder.SetInsertPoint(BB);
  
      auto fnp = BB->getFirstNonPHI();
      assert(fnp == nullptr);
  
      // This can lead to UB!
      if (BB->isLandingPad()) {
          // do something
      }
  
      return 0;
  }

This patch fixes this by using `isa_and_nonnull` instead of `isa`, which would result in `isLandingPad` always returning `false` when called on an empty BasicBlock. If there is a reason (e.g. performance) for not using `isa_and_nonnull` we could alternatively document that `isLandingPad` should not be called without checking `getFirstNonPHI != nullptr` first, which would avoid people making the same mistake I made.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D75600

Files:
  llvm/lib/IR/BasicBlock.cpp


Index: llvm/lib/IR/BasicBlock.cpp
===================================================================
--- llvm/lib/IR/BasicBlock.cpp
+++ llvm/lib/IR/BasicBlock.cpp
@@ -486,7 +486,7 @@
 /// Return true if this basic block is a landing pad. I.e., it's
 /// the destination of the 'unwind' edge of an invoke instruction.
 bool BasicBlock::isLandingPad() const {
-  return isa<LandingPadInst>(getFirstNonPHI());
+  return isa_and_nonnull<LandingPadInst>(getFirstNonPHI());
 }
 
 /// Return the landingpad instruction associated with the landing pad.


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D75600.248137.patch
Type: text/x-patch
Size: 546 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20200304/278f2758/attachment.bin>


More information about the llvm-commits mailing list