1 //===--- ExpandMemCmp.cpp - Expand memcmp() to load/stores ----------------===// 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 // This pass tries to expand memcmp() calls into optimally-sized loads and 10 // compares for the target. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ADT/Statistic.h" 15 #include "llvm/Analysis/ConstantFolding.h" 16 #include "llvm/Analysis/TargetLibraryInfo.h" 17 #include "llvm/Analysis/TargetTransformInfo.h" 18 #include "llvm/Analysis/ValueTracking.h" 19 #include "llvm/CodeGen/TargetLowering.h" 20 #include "llvm/CodeGen/TargetPassConfig.h" 21 #include "llvm/CodeGen/TargetSubtargetInfo.h" 22 #include "llvm/IR/IRBuilder.h" 23 24 using namespace llvm; 25 26 #define DEBUG_TYPE "expandmemcmp" 27 28 STATISTIC(NumMemCmpCalls, "Number of memcmp calls"); 29 STATISTIC(NumMemCmpNotConstant, "Number of memcmp calls without constant size"); 30 STATISTIC(NumMemCmpGreaterThanMax, 31 "Number of memcmp calls with size greater than max size"); 32 STATISTIC(NumMemCmpInlined, "Number of inlined memcmp calls"); 33 34 static cl::opt<unsigned> MemCmpEqZeroNumLoadsPerBlock( 35 "memcmp-num-loads-per-block", cl::Hidden, cl::init(1), 36 cl::desc("The number of loads per basic block for inline expansion of " 37 "memcmp that is only being compared against zero.")); 38 39 static cl::opt<unsigned> MaxLoadsPerMemcmp( 40 "max-loads-per-memcmp", cl::Hidden, 41 cl::desc("Set maximum number of loads used in expanded memcmp")); 42 43 static cl::opt<unsigned> MaxLoadsPerMemcmpOptSize( 44 "max-loads-per-memcmp-opt-size", cl::Hidden, 45 cl::desc("Set maximum number of loads used in expanded memcmp for -Os/Oz")); 46 47 namespace { 48 49 50 // This class provides helper functions to expand a memcmp library call into an 51 // inline expansion. 52 class MemCmpExpansion { 53 struct ResultBlock { 54 BasicBlock *BB = nullptr; 55 PHINode *PhiSrc1 = nullptr; 56 PHINode *PhiSrc2 = nullptr; 57 58 ResultBlock() = default; 59 }; 60 61 CallInst *const CI; 62 ResultBlock ResBlock; 63 const uint64_t Size; 64 unsigned MaxLoadSize; 65 uint64_t NumLoadsNonOneByte; 66 const uint64_t NumLoadsPerBlockForZeroCmp; 67 std::vector<BasicBlock *> LoadCmpBlocks; 68 BasicBlock *EndBlock; 69 PHINode *PhiRes; 70 const bool IsUsedForZeroCmp; 71 const DataLayout &DL; 72 IRBuilder<> Builder; 73 // Represents the decomposition in blocks of the expansion. For example, 74 // comparing 33 bytes on X86+sse can be done with 2x16-byte loads and 75 // 1x1-byte load, which would be represented as [{16, 0}, {16, 16}, {32, 1}. 76 struct LoadEntry { 77 LoadEntry(unsigned LoadSize, uint64_t Offset) 78 : LoadSize(LoadSize), Offset(Offset) { 79 } 80 81 // The size of the load for this block, in bytes. 82 unsigned LoadSize; 83 // The offset of this load from the base pointer, in bytes. 84 uint64_t Offset; 85 }; 86 using LoadEntryVector = SmallVector<LoadEntry, 8>; 87 LoadEntryVector LoadSequence; 88 89 void createLoadCmpBlocks(); 90 void createResultBlock(); 91 void setupResultBlockPHINodes(); 92 void setupEndBlockPHINodes(); 93 Value *getCompareLoadPairs(unsigned BlockIndex, unsigned &LoadIndex); 94 void emitLoadCompareBlock(unsigned BlockIndex); 95 void emitLoadCompareBlockMultipleLoads(unsigned BlockIndex, 96 unsigned &LoadIndex); 97 void emitLoadCompareByteBlock(unsigned BlockIndex, unsigned OffsetBytes); 98 void emitMemCmpResultBlock(); 99 Value *getMemCmpExpansionZeroCase(); 100 Value *getMemCmpEqZeroOneBlock(); 101 Value *getMemCmpOneBlock(); 102 Value *getPtrToElementAtOffset(Value *Source, Type *LoadSizeType, 103 uint64_t OffsetBytes); 104 105 static LoadEntryVector 106 computeGreedyLoadSequence(uint64_t Size, llvm::ArrayRef<unsigned> LoadSizes, 107 unsigned MaxNumLoads, unsigned &NumLoadsNonOneByte); 108 static LoadEntryVector 109 computeOverlappingLoadSequence(uint64_t Size, unsigned MaxLoadSize, 110 unsigned MaxNumLoads, 111 unsigned &NumLoadsNonOneByte); 112 113 public: 114 MemCmpExpansion(CallInst *CI, uint64_t Size, 115 const TargetTransformInfo::MemCmpExpansionOptions &Options, 116 const bool IsUsedForZeroCmp, const DataLayout &TheDataLayout); 117 118 unsigned getNumBlocks(); 119 uint64_t getNumLoads() const { return LoadSequence.size(); } 120 121 Value *getMemCmpExpansion(); 122 }; 123 124 MemCmpExpansion::LoadEntryVector MemCmpExpansion::computeGreedyLoadSequence( 125 uint64_t Size, llvm::ArrayRef<unsigned> LoadSizes, 126 const unsigned MaxNumLoads, unsigned &NumLoadsNonOneByte) { 127 NumLoadsNonOneByte = 0; 128 LoadEntryVector LoadSequence; 129 uint64_t Offset = 0; 130 while (Size && !LoadSizes.empty()) { 131 const unsigned LoadSize = LoadSizes.front(); 132 const uint64_t NumLoadsForThisSize = Size / LoadSize; 133 if (LoadSequence.size() + NumLoadsForThisSize > MaxNumLoads) { 134 // Do not expand if the total number of loads is larger than what the 135 // target allows. Note that it's important that we exit before completing 136 // the expansion to avoid using a ton of memory to store the expansion for 137 // large sizes. 138 return {}; 139 } 140 if (NumLoadsForThisSize > 0) { 141 for (uint64_t I = 0; I < NumLoadsForThisSize; ++I) { 142 LoadSequence.push_back({LoadSize, Offset}); 143 Offset += LoadSize; 144 } 145 if (LoadSize > 1) 146 ++NumLoadsNonOneByte; 147 Size = Size % LoadSize; 148 } 149 LoadSizes = LoadSizes.drop_front(); 150 } 151 return LoadSequence; 152 } 153 154 MemCmpExpansion::LoadEntryVector 155 MemCmpExpansion::computeOverlappingLoadSequence(uint64_t Size, 156 const unsigned MaxLoadSize, 157 const unsigned MaxNumLoads, 158 unsigned &NumLoadsNonOneByte) { 159 // These are already handled by the greedy approach. 160 if (Size < 2 || MaxLoadSize < 2) 161 return {}; 162 163 // We try to do as many non-overlapping loads as possible starting from the 164 // beginning. 165 const uint64_t NumNonOverlappingLoads = Size / MaxLoadSize; 166 assert(NumNonOverlappingLoads && "there must be at least one load"); 167 // There remain 0 to (MaxLoadSize - 1) bytes to load, this will be done with 168 // an overlapping load. 169 Size = Size - NumNonOverlappingLoads * MaxLoadSize; 170 // Bail if we do not need an overloapping store, this is already handled by 171 // the greedy approach. 172 if (Size == 0) 173 return {}; 174 // Bail if the number of loads (non-overlapping + potential overlapping one) 175 // is larger than the max allowed. 176 if ((NumNonOverlappingLoads + 1) > MaxNumLoads) 177 return {}; 178 179 // Add non-overlapping loads. 180 LoadEntryVector LoadSequence; 181 uint64_t Offset = 0; 182 for (uint64_t I = 0; I < NumNonOverlappingLoads; ++I) { 183 LoadSequence.push_back({MaxLoadSize, Offset}); 184 Offset += MaxLoadSize; 185 } 186 187 // Add the last overlapping load. 188 assert(Size > 0 && Size < MaxLoadSize && "broken invariant"); 189 LoadSequence.push_back({MaxLoadSize, Offset - (MaxLoadSize - Size)}); 190 NumLoadsNonOneByte = 1; 191 return LoadSequence; 192 } 193 194 // Initialize the basic block structure required for expansion of memcmp call 195 // with given maximum load size and memcmp size parameter. 196 // This structure includes: 197 // 1. A list of load compare blocks - LoadCmpBlocks. 198 // 2. An EndBlock, split from original instruction point, which is the block to 199 // return from. 200 // 3. ResultBlock, block to branch to for early exit when a 201 // LoadCmpBlock finds a difference. 202 MemCmpExpansion::MemCmpExpansion( 203 CallInst *const CI, uint64_t Size, 204 const TargetTransformInfo::MemCmpExpansionOptions &Options, 205 const bool IsUsedForZeroCmp, const DataLayout &TheDataLayout) 206 : CI(CI), Size(Size), MaxLoadSize(0), NumLoadsNonOneByte(0), 207 NumLoadsPerBlockForZeroCmp(Options.NumLoadsPerBlock), 208 IsUsedForZeroCmp(IsUsedForZeroCmp), DL(TheDataLayout), Builder(CI) { 209 assert(Size > 0 && "zero blocks"); 210 // Scale the max size down if the target can load more bytes than we need. 211 llvm::ArrayRef<unsigned> LoadSizes(Options.LoadSizes); 212 while (!LoadSizes.empty() && LoadSizes.front() > Size) { 213 LoadSizes = LoadSizes.drop_front(); 214 } 215 assert(!LoadSizes.empty() && "cannot load Size bytes"); 216 MaxLoadSize = LoadSizes.front(); 217 // Compute the decomposition. 218 unsigned GreedyNumLoadsNonOneByte = 0; 219 LoadSequence = computeGreedyLoadSequence(Size, LoadSizes, Options.MaxNumLoads, 220 GreedyNumLoadsNonOneByte); 221 NumLoadsNonOneByte = GreedyNumLoadsNonOneByte; 222 assert(LoadSequence.size() <= Options.MaxNumLoads && "broken invariant"); 223 // If we allow overlapping loads and the load sequence is not already optimal, 224 // use overlapping loads. 225 if (Options.AllowOverlappingLoads && 226 (LoadSequence.empty() || LoadSequence.size() > 2)) { 227 unsigned OverlappingNumLoadsNonOneByte = 0; 228 auto OverlappingLoads = computeOverlappingLoadSequence( 229 Size, MaxLoadSize, Options.MaxNumLoads, OverlappingNumLoadsNonOneByte); 230 if (!OverlappingLoads.empty() && 231 (LoadSequence.empty() || 232 OverlappingLoads.size() < LoadSequence.size())) { 233 LoadSequence = OverlappingLoads; 234 NumLoadsNonOneByte = OverlappingNumLoadsNonOneByte; 235 } 236 } 237 assert(LoadSequence.size() <= Options.MaxNumLoads && "broken invariant"); 238 } 239 240 unsigned MemCmpExpansion::getNumBlocks() { 241 if (IsUsedForZeroCmp) 242 return getNumLoads() / NumLoadsPerBlockForZeroCmp + 243 (getNumLoads() % NumLoadsPerBlockForZeroCmp != 0 ? 1 : 0); 244 return getNumLoads(); 245 } 246 247 void MemCmpExpansion::createLoadCmpBlocks() { 248 for (unsigned i = 0; i < getNumBlocks(); i++) { 249 BasicBlock *BB = BasicBlock::Create(CI->getContext(), "loadbb", 250 EndBlock->getParent(), EndBlock); 251 LoadCmpBlocks.push_back(BB); 252 } 253 } 254 255 void MemCmpExpansion::createResultBlock() { 256 ResBlock.BB = BasicBlock::Create(CI->getContext(), "res_block", 257 EndBlock->getParent(), EndBlock); 258 } 259 260 /// Return a pointer to an element of type `LoadSizeType` at offset 261 /// `OffsetBytes`. 262 Value *MemCmpExpansion::getPtrToElementAtOffset(Value *Source, 263 Type *LoadSizeType, 264 uint64_t OffsetBytes) { 265 if (OffsetBytes > 0) { 266 auto *ByteType = Type::getInt8Ty(CI->getContext()); 267 Source = Builder.CreateGEP( 268 ByteType, Builder.CreateBitCast(Source, ByteType->getPointerTo()), 269 ConstantInt::get(ByteType, OffsetBytes)); 270 } 271 return Builder.CreateBitCast(Source, LoadSizeType->getPointerTo()); 272 } 273 274 // This function creates the IR instructions for loading and comparing 1 byte. 275 // It loads 1 byte from each source of the memcmp parameters with the given 276 // GEPIndex. It then subtracts the two loaded values and adds this result to the 277 // final phi node for selecting the memcmp result. 278 void MemCmpExpansion::emitLoadCompareByteBlock(unsigned BlockIndex, 279 unsigned OffsetBytes) { 280 Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]); 281 Type *LoadSizeType = Type::getInt8Ty(CI->getContext()); 282 Value *Source1 = 283 getPtrToElementAtOffset(CI->getArgOperand(0), LoadSizeType, OffsetBytes); 284 Value *Source2 = 285 getPtrToElementAtOffset(CI->getArgOperand(1), LoadSizeType, OffsetBytes); 286 287 Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1); 288 Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2); 289 290 LoadSrc1 = Builder.CreateZExt(LoadSrc1, Type::getInt32Ty(CI->getContext())); 291 LoadSrc2 = Builder.CreateZExt(LoadSrc2, Type::getInt32Ty(CI->getContext())); 292 Value *Diff = Builder.CreateSub(LoadSrc1, LoadSrc2); 293 294 PhiRes->addIncoming(Diff, LoadCmpBlocks[BlockIndex]); 295 296 if (BlockIndex < (LoadCmpBlocks.size() - 1)) { 297 // Early exit branch if difference found to EndBlock. Otherwise, continue to 298 // next LoadCmpBlock, 299 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff, 300 ConstantInt::get(Diff->getType(), 0)); 301 BranchInst *CmpBr = 302 BranchInst::Create(EndBlock, LoadCmpBlocks[BlockIndex + 1], Cmp); 303 Builder.Insert(CmpBr); 304 } else { 305 // The last block has an unconditional branch to EndBlock. 306 BranchInst *CmpBr = BranchInst::Create(EndBlock); 307 Builder.Insert(CmpBr); 308 } 309 } 310 311 /// Generate an equality comparison for one or more pairs of loaded values. 312 /// This is used in the case where the memcmp() call is compared equal or not 313 /// equal to zero. 314 Value *MemCmpExpansion::getCompareLoadPairs(unsigned BlockIndex, 315 unsigned &LoadIndex) { 316 assert(LoadIndex < getNumLoads() && 317 "getCompareLoadPairs() called with no remaining loads"); 318 std::vector<Value *> XorList, OrList; 319 Value *Diff = nullptr; 320 321 const unsigned NumLoads = 322 std::min(getNumLoads() - LoadIndex, NumLoadsPerBlockForZeroCmp); 323 324 // For a single-block expansion, start inserting before the memcmp call. 325 if (LoadCmpBlocks.empty()) 326 Builder.SetInsertPoint(CI); 327 else 328 Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]); 329 330 Value *Cmp = nullptr; 331 // If we have multiple loads per block, we need to generate a composite 332 // comparison using xor+or. The type for the combinations is the largest load 333 // type. 334 IntegerType *const MaxLoadType = 335 NumLoads == 1 ? nullptr 336 : IntegerType::get(CI->getContext(), MaxLoadSize * 8); 337 for (unsigned i = 0; i < NumLoads; ++i, ++LoadIndex) { 338 const LoadEntry &CurLoadEntry = LoadSequence[LoadIndex]; 339 340 IntegerType *LoadSizeType = 341 IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8); 342 343 Value *Source1 = getPtrToElementAtOffset(CI->getArgOperand(0), LoadSizeType, 344 CurLoadEntry.Offset); 345 Value *Source2 = getPtrToElementAtOffset(CI->getArgOperand(1), LoadSizeType, 346 CurLoadEntry.Offset); 347 348 // Get a constant or load a value for each source address. 349 Value *LoadSrc1 = nullptr; 350 if (auto *Source1C = dyn_cast<Constant>(Source1)) 351 LoadSrc1 = ConstantFoldLoadFromConstPtr(Source1C, LoadSizeType, DL); 352 if (!LoadSrc1) 353 LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1); 354 355 Value *LoadSrc2 = nullptr; 356 if (auto *Source2C = dyn_cast<Constant>(Source2)) 357 LoadSrc2 = ConstantFoldLoadFromConstPtr(Source2C, LoadSizeType, DL); 358 if (!LoadSrc2) 359 LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2); 360 361 if (NumLoads != 1) { 362 if (LoadSizeType != MaxLoadType) { 363 LoadSrc1 = Builder.CreateZExt(LoadSrc1, MaxLoadType); 364 LoadSrc2 = Builder.CreateZExt(LoadSrc2, MaxLoadType); 365 } 366 // If we have multiple loads per block, we need to generate a composite 367 // comparison using xor+or. 368 Diff = Builder.CreateXor(LoadSrc1, LoadSrc2); 369 Diff = Builder.CreateZExt(Diff, MaxLoadType); 370 XorList.push_back(Diff); 371 } else { 372 // If there's only one load per block, we just compare the loaded values. 373 Cmp = Builder.CreateICmpNE(LoadSrc1, LoadSrc2); 374 } 375 } 376 377 auto pairWiseOr = [&](std::vector<Value *> &InList) -> std::vector<Value *> { 378 std::vector<Value *> OutList; 379 for (unsigned i = 0; i < InList.size() - 1; i = i + 2) { 380 Value *Or = Builder.CreateOr(InList[i], InList[i + 1]); 381 OutList.push_back(Or); 382 } 383 if (InList.size() % 2 != 0) 384 OutList.push_back(InList.back()); 385 return OutList; 386 }; 387 388 if (!Cmp) { 389 // Pairwise OR the XOR results. 390 OrList = pairWiseOr(XorList); 391 392 // Pairwise OR the OR results until one result left. 393 while (OrList.size() != 1) { 394 OrList = pairWiseOr(OrList); 395 } 396 397 assert(Diff && "Failed to find comparison diff"); 398 Cmp = Builder.CreateICmpNE(OrList[0], ConstantInt::get(Diff->getType(), 0)); 399 } 400 401 return Cmp; 402 } 403 404 void MemCmpExpansion::emitLoadCompareBlockMultipleLoads(unsigned BlockIndex, 405 unsigned &LoadIndex) { 406 Value *Cmp = getCompareLoadPairs(BlockIndex, LoadIndex); 407 408 BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1)) 409 ? EndBlock 410 : LoadCmpBlocks[BlockIndex + 1]; 411 // Early exit branch if difference found to ResultBlock. Otherwise, 412 // continue to next LoadCmpBlock or EndBlock. 413 BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp); 414 Builder.Insert(CmpBr); 415 416 // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0 417 // since early exit to ResultBlock was not taken (no difference was found in 418 // any of the bytes). 419 if (BlockIndex == LoadCmpBlocks.size() - 1) { 420 Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0); 421 PhiRes->addIncoming(Zero, LoadCmpBlocks[BlockIndex]); 422 } 423 } 424 425 // This function creates the IR intructions for loading and comparing using the 426 // given LoadSize. It loads the number of bytes specified by LoadSize from each 427 // source of the memcmp parameters. It then does a subtract to see if there was 428 // a difference in the loaded values. If a difference is found, it branches 429 // with an early exit to the ResultBlock for calculating which source was 430 // larger. Otherwise, it falls through to the either the next LoadCmpBlock or 431 // the EndBlock if this is the last LoadCmpBlock. Loading 1 byte is handled with 432 // a special case through emitLoadCompareByteBlock. The special handling can 433 // simply subtract the loaded values and add it to the result phi node. 434 void MemCmpExpansion::emitLoadCompareBlock(unsigned BlockIndex) { 435 // There is one load per block in this case, BlockIndex == LoadIndex. 436 const LoadEntry &CurLoadEntry = LoadSequence[BlockIndex]; 437 438 if (CurLoadEntry.LoadSize == 1) { 439 MemCmpExpansion::emitLoadCompareByteBlock(BlockIndex, CurLoadEntry.Offset); 440 return; 441 } 442 443 Type *LoadSizeType = 444 IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8); 445 Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8); 446 assert(CurLoadEntry.LoadSize <= MaxLoadSize && "Unexpected load type"); 447 448 Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]); 449 450 Value *Source1 = getPtrToElementAtOffset(CI->getArgOperand(0), LoadSizeType, 451 CurLoadEntry.Offset); 452 Value *Source2 = getPtrToElementAtOffset(CI->getArgOperand(1), LoadSizeType, 453 CurLoadEntry.Offset); 454 455 // Load LoadSizeType from the base address. 456 Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1); 457 Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2); 458 459 if (DL.isLittleEndian()) { 460 Function *Bswap = Intrinsic::getDeclaration(CI->getModule(), 461 Intrinsic::bswap, LoadSizeType); 462 LoadSrc1 = Builder.CreateCall(Bswap, LoadSrc1); 463 LoadSrc2 = Builder.CreateCall(Bswap, LoadSrc2); 464 } 465 466 if (LoadSizeType != MaxLoadType) { 467 LoadSrc1 = Builder.CreateZExt(LoadSrc1, MaxLoadType); 468 LoadSrc2 = Builder.CreateZExt(LoadSrc2, MaxLoadType); 469 } 470 471 // Add the loaded values to the phi nodes for calculating memcmp result only 472 // if result is not used in a zero equality. 473 if (!IsUsedForZeroCmp) { 474 ResBlock.PhiSrc1->addIncoming(LoadSrc1, LoadCmpBlocks[BlockIndex]); 475 ResBlock.PhiSrc2->addIncoming(LoadSrc2, LoadCmpBlocks[BlockIndex]); 476 } 477 478 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, LoadSrc1, LoadSrc2); 479 BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1)) 480 ? EndBlock 481 : LoadCmpBlocks[BlockIndex + 1]; 482 // Early exit branch if difference found to ResultBlock. Otherwise, continue 483 // to next LoadCmpBlock or EndBlock. 484 BranchInst *CmpBr = BranchInst::Create(NextBB, ResBlock.BB, Cmp); 485 Builder.Insert(CmpBr); 486 487 // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0 488 // since early exit to ResultBlock was not taken (no difference was found in 489 // any of the bytes). 490 if (BlockIndex == LoadCmpBlocks.size() - 1) { 491 Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0); 492 PhiRes->addIncoming(Zero, LoadCmpBlocks[BlockIndex]); 493 } 494 } 495 496 // This function populates the ResultBlock with a sequence to calculate the 497 // memcmp result. It compares the two loaded source values and returns -1 if 498 // src1 < src2 and 1 if src1 > src2. 499 void MemCmpExpansion::emitMemCmpResultBlock() { 500 // Special case: if memcmp result is used in a zero equality, result does not 501 // need to be calculated and can simply return 1. 502 if (IsUsedForZeroCmp) { 503 BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt(); 504 Builder.SetInsertPoint(ResBlock.BB, InsertPt); 505 Value *Res = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 1); 506 PhiRes->addIncoming(Res, ResBlock.BB); 507 BranchInst *NewBr = BranchInst::Create(EndBlock); 508 Builder.Insert(NewBr); 509 return; 510 } 511 BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt(); 512 Builder.SetInsertPoint(ResBlock.BB, InsertPt); 513 514 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_ULT, ResBlock.PhiSrc1, 515 ResBlock.PhiSrc2); 516 517 Value *Res = 518 Builder.CreateSelect(Cmp, ConstantInt::get(Builder.getInt32Ty(), -1), 519 ConstantInt::get(Builder.getInt32Ty(), 1)); 520 521 BranchInst *NewBr = BranchInst::Create(EndBlock); 522 Builder.Insert(NewBr); 523 PhiRes->addIncoming(Res, ResBlock.BB); 524 } 525 526 void MemCmpExpansion::setupResultBlockPHINodes() { 527 Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8); 528 Builder.SetInsertPoint(ResBlock.BB); 529 // Note: this assumes one load per block. 530 ResBlock.PhiSrc1 = 531 Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src1"); 532 ResBlock.PhiSrc2 = 533 Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src2"); 534 } 535 536 void MemCmpExpansion::setupEndBlockPHINodes() { 537 Builder.SetInsertPoint(&EndBlock->front()); 538 PhiRes = Builder.CreatePHI(Type::getInt32Ty(CI->getContext()), 2, "phi.res"); 539 } 540 541 Value *MemCmpExpansion::getMemCmpExpansionZeroCase() { 542 unsigned LoadIndex = 0; 543 // This loop populates each of the LoadCmpBlocks with the IR sequence to 544 // handle multiple loads per block. 545 for (unsigned I = 0; I < getNumBlocks(); ++I) { 546 emitLoadCompareBlockMultipleLoads(I, LoadIndex); 547 } 548 549 emitMemCmpResultBlock(); 550 return PhiRes; 551 } 552 553 /// A memcmp expansion that compares equality with 0 and only has one block of 554 /// load and compare can bypass the compare, branch, and phi IR that is required 555 /// in the general case. 556 Value *MemCmpExpansion::getMemCmpEqZeroOneBlock() { 557 unsigned LoadIndex = 0; 558 Value *Cmp = getCompareLoadPairs(0, LoadIndex); 559 assert(LoadIndex == getNumLoads() && "some entries were not consumed"); 560 return Builder.CreateZExt(Cmp, Type::getInt32Ty(CI->getContext())); 561 } 562 563 /// A memcmp expansion that only has one block of load and compare can bypass 564 /// the compare, branch, and phi IR that is required in the general case. 565 Value *MemCmpExpansion::getMemCmpOneBlock() { 566 Type *LoadSizeType = IntegerType::get(CI->getContext(), Size * 8); 567 Value *Source1 = CI->getArgOperand(0); 568 Value *Source2 = CI->getArgOperand(1); 569 570 // Cast source to LoadSizeType*. 571 if (Source1->getType() != LoadSizeType) 572 Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo()); 573 if (Source2->getType() != LoadSizeType) 574 Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo()); 575 576 // Load LoadSizeType from the base address. 577 Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1); 578 Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2); 579 580 if (DL.isLittleEndian() && Size != 1) { 581 Function *Bswap = Intrinsic::getDeclaration(CI->getModule(), 582 Intrinsic::bswap, LoadSizeType); 583 LoadSrc1 = Builder.CreateCall(Bswap, LoadSrc1); 584 LoadSrc2 = Builder.CreateCall(Bswap, LoadSrc2); 585 } 586 587 if (Size < 4) { 588 // The i8 and i16 cases don't need compares. We zext the loaded values and 589 // subtract them to get the suitable negative, zero, or positive i32 result. 590 LoadSrc1 = Builder.CreateZExt(LoadSrc1, Builder.getInt32Ty()); 591 LoadSrc2 = Builder.CreateZExt(LoadSrc2, Builder.getInt32Ty()); 592 return Builder.CreateSub(LoadSrc1, LoadSrc2); 593 } 594 595 // The result of memcmp is negative, zero, or positive, so produce that by 596 // subtracting 2 extended compare bits: sub (ugt, ult). 597 // If a target prefers to use selects to get -1/0/1, they should be able 598 // to transform this later. The inverse transform (going from selects to math) 599 // may not be possible in the DAG because the selects got converted into 600 // branches before we got there. 601 Value *CmpUGT = Builder.CreateICmpUGT(LoadSrc1, LoadSrc2); 602 Value *CmpULT = Builder.CreateICmpULT(LoadSrc1, LoadSrc2); 603 Value *ZextUGT = Builder.CreateZExt(CmpUGT, Builder.getInt32Ty()); 604 Value *ZextULT = Builder.CreateZExt(CmpULT, Builder.getInt32Ty()); 605 return Builder.CreateSub(ZextUGT, ZextULT); 606 } 607 608 // This function expands the memcmp call into an inline expansion and returns 609 // the memcmp result. 610 Value *MemCmpExpansion::getMemCmpExpansion() { 611 // Create the basic block framework for a multi-block expansion. 612 if (getNumBlocks() != 1) { 613 BasicBlock *StartBlock = CI->getParent(); 614 EndBlock = StartBlock->splitBasicBlock(CI, "endblock"); 615 setupEndBlockPHINodes(); 616 createResultBlock(); 617 618 // If return value of memcmp is not used in a zero equality, we need to 619 // calculate which source was larger. The calculation requires the 620 // two loaded source values of each load compare block. 621 // These will be saved in the phi nodes created by setupResultBlockPHINodes. 622 if (!IsUsedForZeroCmp) setupResultBlockPHINodes(); 623 624 // Create the number of required load compare basic blocks. 625 createLoadCmpBlocks(); 626 627 // Update the terminator added by splitBasicBlock to branch to the first 628 // LoadCmpBlock. 629 StartBlock->getTerminator()->setSuccessor(0, LoadCmpBlocks[0]); 630 } 631 632 Builder.SetCurrentDebugLocation(CI->getDebugLoc()); 633 634 if (IsUsedForZeroCmp) 635 return getNumBlocks() == 1 ? getMemCmpEqZeroOneBlock() 636 : getMemCmpExpansionZeroCase(); 637 638 if (getNumBlocks() == 1) 639 return getMemCmpOneBlock(); 640 641 for (unsigned I = 0; I < getNumBlocks(); ++I) { 642 emitLoadCompareBlock(I); 643 } 644 645 emitMemCmpResultBlock(); 646 return PhiRes; 647 } 648 649 // This function checks to see if an expansion of memcmp can be generated. 650 // It checks for constant compare size that is less than the max inline size. 651 // If an expansion cannot occur, returns false to leave as a library call. 652 // Otherwise, the library call is replaced with a new IR instruction sequence. 653 /// We want to transform: 654 /// %call = call signext i32 @memcmp(i8* %0, i8* %1, i64 15) 655 /// To: 656 /// loadbb: 657 /// %0 = bitcast i32* %buffer2 to i8* 658 /// %1 = bitcast i32* %buffer1 to i8* 659 /// %2 = bitcast i8* %1 to i64* 660 /// %3 = bitcast i8* %0 to i64* 661 /// %4 = load i64, i64* %2 662 /// %5 = load i64, i64* %3 663 /// %6 = call i64 @llvm.bswap.i64(i64 %4) 664 /// %7 = call i64 @llvm.bswap.i64(i64 %5) 665 /// %8 = sub i64 %6, %7 666 /// %9 = icmp ne i64 %8, 0 667 /// br i1 %9, label %res_block, label %loadbb1 668 /// res_block: ; preds = %loadbb2, 669 /// %loadbb1, %loadbb 670 /// %phi.src1 = phi i64 [ %6, %loadbb ], [ %22, %loadbb1 ], [ %36, %loadbb2 ] 671 /// %phi.src2 = phi i64 [ %7, %loadbb ], [ %23, %loadbb1 ], [ %37, %loadbb2 ] 672 /// %10 = icmp ult i64 %phi.src1, %phi.src2 673 /// %11 = select i1 %10, i32 -1, i32 1 674 /// br label %endblock 675 /// loadbb1: ; preds = %loadbb 676 /// %12 = bitcast i32* %buffer2 to i8* 677 /// %13 = bitcast i32* %buffer1 to i8* 678 /// %14 = bitcast i8* %13 to i32* 679 /// %15 = bitcast i8* %12 to i32* 680 /// %16 = getelementptr i32, i32* %14, i32 2 681 /// %17 = getelementptr i32, i32* %15, i32 2 682 /// %18 = load i32, i32* %16 683 /// %19 = load i32, i32* %17 684 /// %20 = call i32 @llvm.bswap.i32(i32 %18) 685 /// %21 = call i32 @llvm.bswap.i32(i32 %19) 686 /// %22 = zext i32 %20 to i64 687 /// %23 = zext i32 %21 to i64 688 /// %24 = sub i64 %22, %23 689 /// %25 = icmp ne i64 %24, 0 690 /// br i1 %25, label %res_block, label %loadbb2 691 /// loadbb2: ; preds = %loadbb1 692 /// %26 = bitcast i32* %buffer2 to i8* 693 /// %27 = bitcast i32* %buffer1 to i8* 694 /// %28 = bitcast i8* %27 to i16* 695 /// %29 = bitcast i8* %26 to i16* 696 /// %30 = getelementptr i16, i16* %28, i16 6 697 /// %31 = getelementptr i16, i16* %29, i16 6 698 /// %32 = load i16, i16* %30 699 /// %33 = load i16, i16* %31 700 /// %34 = call i16 @llvm.bswap.i16(i16 %32) 701 /// %35 = call i16 @llvm.bswap.i16(i16 %33) 702 /// %36 = zext i16 %34 to i64 703 /// %37 = zext i16 %35 to i64 704 /// %38 = sub i64 %36, %37 705 /// %39 = icmp ne i64 %38, 0 706 /// br i1 %39, label %res_block, label %loadbb3 707 /// loadbb3: ; preds = %loadbb2 708 /// %40 = bitcast i32* %buffer2 to i8* 709 /// %41 = bitcast i32* %buffer1 to i8* 710 /// %42 = getelementptr i8, i8* %41, i8 14 711 /// %43 = getelementptr i8, i8* %40, i8 14 712 /// %44 = load i8, i8* %42 713 /// %45 = load i8, i8* %43 714 /// %46 = zext i8 %44 to i32 715 /// %47 = zext i8 %45 to i32 716 /// %48 = sub i32 %46, %47 717 /// br label %endblock 718 /// endblock: ; preds = %res_block, 719 /// %loadbb3 720 /// %phi.res = phi i32 [ %48, %loadbb3 ], [ %11, %res_block ] 721 /// ret i32 %phi.res 722 static bool expandMemCmp(CallInst *CI, const TargetTransformInfo *TTI, 723 const TargetLowering *TLI, const DataLayout *DL) { 724 NumMemCmpCalls++; 725 726 // Early exit from expansion if -Oz. 727 if (CI->getFunction()->hasMinSize()) 728 return false; 729 730 // Early exit from expansion if size is not a constant. 731 ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2)); 732 if (!SizeCast) { 733 NumMemCmpNotConstant++; 734 return false; 735 } 736 const uint64_t SizeVal = SizeCast->getZExtValue(); 737 738 if (SizeVal == 0) { 739 return false; 740 } 741 // TTI call to check if target would like to expand memcmp. Also, get the 742 // available load sizes. 743 const bool IsUsedForZeroCmp = isOnlyUsedInZeroEqualityComparison(CI); 744 auto Options = TTI->enableMemCmpExpansion(CI->getFunction()->hasOptSize(), 745 IsUsedForZeroCmp); 746 if (!Options) return false; 747 748 if (MemCmpEqZeroNumLoadsPerBlock.getNumOccurrences()) 749 Options.NumLoadsPerBlock = MemCmpEqZeroNumLoadsPerBlock; 750 751 if (CI->getFunction()->hasOptSize() && 752 MaxLoadsPerMemcmpOptSize.getNumOccurrences()) 753 Options.MaxNumLoads = MaxLoadsPerMemcmpOptSize; 754 755 if (!CI->getFunction()->hasOptSize() && MaxLoadsPerMemcmp.getNumOccurrences()) 756 Options.MaxNumLoads = MaxLoadsPerMemcmp; 757 758 MemCmpExpansion Expansion(CI, SizeVal, Options, IsUsedForZeroCmp, *DL); 759 760 // Don't expand if this will require more loads than desired by the target. 761 if (Expansion.getNumLoads() == 0) { 762 NumMemCmpGreaterThanMax++; 763 return false; 764 } 765 766 NumMemCmpInlined++; 767 768 Value *Res = Expansion.getMemCmpExpansion(); 769 770 // Replace call with result of expansion and erase call. 771 CI->replaceAllUsesWith(Res); 772 CI->eraseFromParent(); 773 774 return true; 775 } 776 777 778 779 class ExpandMemCmpPass : public FunctionPass { 780 public: 781 static char ID; 782 783 ExpandMemCmpPass() : FunctionPass(ID) { 784 initializeExpandMemCmpPassPass(*PassRegistry::getPassRegistry()); 785 } 786 787 bool runOnFunction(Function &F) override { 788 if (skipFunction(F)) return false; 789 790 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>(); 791 if (!TPC) { 792 return false; 793 } 794 const TargetLowering* TL = 795 TPC->getTM<TargetMachine>().getSubtargetImpl(F)->getTargetLowering(); 796 797 const TargetLibraryInfo *TLI = 798 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 799 const TargetTransformInfo *TTI = 800 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 801 auto PA = runImpl(F, TLI, TTI, TL); 802 return !PA.areAllPreserved(); 803 } 804 805 private: 806 void getAnalysisUsage(AnalysisUsage &AU) const override { 807 AU.addRequired<TargetLibraryInfoWrapperPass>(); 808 AU.addRequired<TargetTransformInfoWrapperPass>(); 809 FunctionPass::getAnalysisUsage(AU); 810 } 811 812 PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI, 813 const TargetTransformInfo *TTI, 814 const TargetLowering* TL); 815 // Returns true if a change was made. 816 bool runOnBlock(BasicBlock &BB, const TargetLibraryInfo *TLI, 817 const TargetTransformInfo *TTI, const TargetLowering* TL, 818 const DataLayout& DL); 819 }; 820 821 bool ExpandMemCmpPass::runOnBlock( 822 BasicBlock &BB, const TargetLibraryInfo *TLI, 823 const TargetTransformInfo *TTI, const TargetLowering* TL, 824 const DataLayout& DL) { 825 for (Instruction& I : BB) { 826 CallInst *CI = dyn_cast<CallInst>(&I); 827 if (!CI) { 828 continue; 829 } 830 LibFunc Func; 831 if (TLI->getLibFunc(ImmutableCallSite(CI), Func) && 832 (Func == LibFunc_memcmp || Func == LibFunc_bcmp) && 833 expandMemCmp(CI, TTI, TL, &DL)) { 834 return true; 835 } 836 } 837 return false; 838 } 839 840 841 PreservedAnalyses ExpandMemCmpPass::runImpl( 842 Function &F, const TargetLibraryInfo *TLI, const TargetTransformInfo *TTI, 843 const TargetLowering* TL) { 844 const DataLayout& DL = F.getParent()->getDataLayout(); 845 bool MadeChanges = false; 846 for (auto BBIt = F.begin(); BBIt != F.end();) { 847 if (runOnBlock(*BBIt, TLI, TTI, TL, DL)) { 848 MadeChanges = true; 849 // If changes were made, restart the function from the beginning, since 850 // the structure of the function was changed. 851 BBIt = F.begin(); 852 } else { 853 ++BBIt; 854 } 855 } 856 return MadeChanges ? PreservedAnalyses::none() : PreservedAnalyses::all(); 857 } 858 859 } // namespace 860 861 char ExpandMemCmpPass::ID = 0; 862 INITIALIZE_PASS_BEGIN(ExpandMemCmpPass, "expandmemcmp", 863 "Expand memcmp() to load/stores", false, false) 864 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 865 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 866 INITIALIZE_PASS_END(ExpandMemCmpPass, "expandmemcmp", 867 "Expand memcmp() to load/stores", false, false) 868 869 FunctionPass *llvm::createExpandMemCmpPass() { 870 return new ExpandMemCmpPass(); 871 } 872