1 //===----- TypePromotion.cpp ----------------------------------------------===// 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 /// \file 10 /// This is an opcode based type promotion pass for small types that would 11 /// otherwise be promoted during legalisation. This works around the limitations 12 /// of selection dag for cyclic regions. The search begins from icmp 13 /// instructions operands where a tree, consisting of non-wrapping or safe 14 /// wrapping instructions, is built, checked and promoted if possible. 15 /// 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/ADT/SetVector.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/Analysis/TargetTransformInfo.h" 21 #include "llvm/CodeGen/Passes.h" 22 #include "llvm/CodeGen/TargetLowering.h" 23 #include "llvm/CodeGen/TargetPassConfig.h" 24 #include "llvm/CodeGen/TargetSubtargetInfo.h" 25 #include "llvm/IR/Attributes.h" 26 #include "llvm/IR/BasicBlock.h" 27 #include "llvm/IR/IRBuilder.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/InstrTypes.h" 31 #include "llvm/IR/Instruction.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/Type.h" 34 #include "llvm/IR/Value.h" 35 #include "llvm/IR/Verifier.h" 36 #include "llvm/InitializePasses.h" 37 #include "llvm/Pass.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Target/TargetMachine.h" 41 42 #define DEBUG_TYPE "type-promotion" 43 #define PASS_NAME "Type Promotion" 44 45 using namespace llvm; 46 47 static cl::opt<bool> 48 DisablePromotion("disable-type-promotion", cl::Hidden, cl::init(false), 49 cl::desc("Disable type promotion pass")); 50 51 // The goal of this pass is to enable more efficient code generation for 52 // operations on narrow types (i.e. types with < 32-bits) and this is a 53 // motivating IR code example: 54 // 55 // define hidden i32 @cmp(i8 zeroext) { 56 // %2 = add i8 %0, -49 57 // %3 = icmp ult i8 %2, 3 58 // .. 59 // } 60 // 61 // The issue here is that i8 is type-legalized to i32 because i8 is not a 62 // legal type. Thus, arithmetic is done in integer-precision, but then the 63 // byte value is masked out as follows: 64 // 65 // t19: i32 = add t4, Constant:i32<-49> 66 // t24: i32 = and t19, Constant:i32<255> 67 // 68 // Consequently, we generate code like this: 69 // 70 // subs r0, #49 71 // uxtb r1, r0 72 // cmp r1, #3 73 // 74 // This shows that masking out the byte value results in generation of 75 // the UXTB instruction. This is not optimal as r0 already contains the byte 76 // value we need, and so instead we can just generate: 77 // 78 // sub.w r1, r0, #49 79 // cmp r1, #3 80 // 81 // We achieve this by type promoting the IR to i32 like so for this example: 82 // 83 // define i32 @cmp(i8 zeroext %c) { 84 // %0 = zext i8 %c to i32 85 // %c.off = add i32 %0, -49 86 // %1 = icmp ult i32 %c.off, 3 87 // .. 88 // } 89 // 90 // For this to be valid and legal, we need to prove that the i32 add is 91 // producing the same value as the i8 addition, and that e.g. no overflow 92 // happens. 93 // 94 // A brief sketch of the algorithm and some terminology. 95 // We pattern match interesting IR patterns: 96 // - which have "sources": instructions producing narrow values (i8, i16), and 97 // - they have "sinks": instructions consuming these narrow values. 98 // 99 // We collect all instruction connecting sources and sinks in a worklist, so 100 // that we can mutate these instruction and perform type promotion when it is 101 // legal to do so. 102 103 namespace { 104 class IRPromoter { 105 LLVMContext &Ctx; 106 IntegerType *OrigTy = nullptr; 107 unsigned PromotedWidth = 0; 108 SetVector<Value*> &Visited; 109 SetVector<Value*> &Sources; 110 SetVector<Instruction*> &Sinks; 111 SmallVectorImpl<Instruction*> &SafeWrap; 112 IntegerType *ExtTy = nullptr; 113 SmallPtrSet<Value*, 8> NewInsts; 114 SmallPtrSet<Instruction*, 4> InstsToRemove; 115 DenseMap<Value*, SmallVector<Type*, 4>> TruncTysMap; 116 SmallPtrSet<Value*, 8> Promoted; 117 118 void ReplaceAllUsersOfWith(Value *From, Value *To); 119 void PrepareWrappingAdds(void); 120 void ExtendSources(void); 121 void ConvertTruncs(void); 122 void PromoteTree(void); 123 void TruncateSinks(void); 124 void Cleanup(void); 125 126 public: 127 IRPromoter(LLVMContext &C, IntegerType *Ty, unsigned Width, 128 SetVector<Value*> &visited, SetVector<Value*> &sources, 129 SetVector<Instruction*> &sinks, 130 SmallVectorImpl<Instruction*> &wrap) : 131 Ctx(C), OrigTy(Ty), PromotedWidth(Width), Visited(visited), 132 Sources(sources), Sinks(sinks), SafeWrap(wrap) { 133 ExtTy = IntegerType::get(Ctx, PromotedWidth); 134 assert(OrigTy->getPrimitiveSizeInBits().getFixedSize() < 135 ExtTy->getPrimitiveSizeInBits().getFixedSize() && 136 "Original type not smaller than extended type"); 137 } 138 139 void Mutate(); 140 }; 141 142 class TypePromotion : public FunctionPass { 143 unsigned TypeSize = 0; 144 LLVMContext *Ctx = nullptr; 145 unsigned RegisterBitWidth = 0; 146 SmallPtrSet<Value*, 16> AllVisited; 147 SmallPtrSet<Instruction*, 8> SafeToPromote; 148 SmallVector<Instruction*, 4> SafeWrap; 149 150 // Does V have the same size result type as TypeSize. 151 bool EqualTypeSize(Value *V); 152 // Does V have the same size, or narrower, result type as TypeSize. 153 bool LessOrEqualTypeSize(Value *V); 154 // Does V have a result type that is wider than TypeSize. 155 bool GreaterThanTypeSize(Value *V); 156 // Does V have a result type that is narrower than TypeSize. 157 bool LessThanTypeSize(Value *V); 158 // Should V be a leaf in the promote tree? 159 bool isSource(Value *V); 160 // Should V be a root in the promotion tree? 161 bool isSink(Value *V); 162 // Should we change the result type of V? It will result in the users of V 163 // being visited. 164 bool shouldPromote(Value *V); 165 // Is I an add or a sub, which isn't marked as nuw, but where a wrapping 166 // result won't affect the computation? 167 bool isSafeWrap(Instruction *I); 168 // Can V have its integer type promoted, or can the type be ignored. 169 bool isSupportedType(Value *V); 170 // Is V an instruction with a supported opcode or another value that we can 171 // handle, such as constants and basic blocks. 172 bool isSupportedValue(Value *V); 173 // Is V an instruction thats result can trivially promoted, or has safe 174 // wrapping. 175 bool isLegalToPromote(Value *V); 176 bool TryToPromote(Value *V, unsigned PromotedWidth); 177 178 public: 179 static char ID; 180 181 TypePromotion() : FunctionPass(ID) {} 182 183 void getAnalysisUsage(AnalysisUsage &AU) const override { 184 AU.addRequired<TargetTransformInfoWrapperPass>(); 185 AU.addRequired<TargetPassConfig>(); 186 AU.setPreservesCFG(); 187 } 188 189 StringRef getPassName() const override { return PASS_NAME; } 190 191 bool runOnFunction(Function &F) override; 192 }; 193 194 } 195 196 static bool GenerateSignBits(Instruction *I) { 197 unsigned Opc = I->getOpcode(); 198 return Opc == Instruction::AShr || Opc == Instruction::SDiv || 199 Opc == Instruction::SRem || Opc == Instruction::SExt; 200 } 201 202 bool TypePromotion::EqualTypeSize(Value *V) { 203 return V->getType()->getScalarSizeInBits() == TypeSize; 204 } 205 206 bool TypePromotion::LessOrEqualTypeSize(Value *V) { 207 return V->getType()->getScalarSizeInBits() <= TypeSize; 208 } 209 210 bool TypePromotion::GreaterThanTypeSize(Value *V) { 211 return V->getType()->getScalarSizeInBits() > TypeSize; 212 } 213 214 bool TypePromotion::LessThanTypeSize(Value *V) { 215 return V->getType()->getScalarSizeInBits() < TypeSize; 216 } 217 218 /// Return true if the given value is a source in the use-def chain, producing 219 /// a narrow 'TypeSize' value. These values will be zext to start the promotion 220 /// of the tree to i32. We guarantee that these won't populate the upper bits 221 /// of the register. ZExt on the loads will be free, and the same for call 222 /// return values because we only accept ones that guarantee a zeroext ret val. 223 /// Many arguments will have the zeroext attribute too, so those would be free 224 /// too. 225 bool TypePromotion::isSource(Value *V) { 226 if (!isa<IntegerType>(V->getType())) 227 return false; 228 229 // TODO Allow zext to be sources. 230 if (isa<Argument>(V)) 231 return true; 232 else if (isa<LoadInst>(V)) 233 return true; 234 else if (isa<BitCastInst>(V)) 235 return true; 236 else if (auto *Call = dyn_cast<CallInst>(V)) 237 return Call->hasRetAttr(Attribute::AttrKind::ZExt); 238 else if (auto *Trunc = dyn_cast<TruncInst>(V)) 239 return EqualTypeSize(Trunc); 240 return false; 241 } 242 243 /// Return true if V will require any promoted values to be truncated for the 244 /// the IR to remain valid. We can't mutate the value type of these 245 /// instructions. 246 bool TypePromotion::isSink(Value *V) { 247 // TODO The truncate also isn't actually necessary because we would already 248 // proved that the data value is kept within the range of the original data 249 // type. 250 251 // Sinks are: 252 // - points where the value in the register is being observed, such as an 253 // icmp, switch or store. 254 // - points where value types have to match, such as calls and returns. 255 // - zext are included to ease the transformation and are generally removed 256 // later on. 257 if (auto *Store = dyn_cast<StoreInst>(V)) 258 return LessOrEqualTypeSize(Store->getValueOperand()); 259 if (auto *Return = dyn_cast<ReturnInst>(V)) 260 return LessOrEqualTypeSize(Return->getReturnValue()); 261 if (auto *ZExt = dyn_cast<ZExtInst>(V)) 262 return GreaterThanTypeSize(ZExt); 263 if (auto *Switch = dyn_cast<SwitchInst>(V)) 264 return LessThanTypeSize(Switch->getCondition()); 265 if (auto *ICmp = dyn_cast<ICmpInst>(V)) 266 return ICmp->isSigned() || LessThanTypeSize(ICmp->getOperand(0)); 267 268 return isa<CallInst>(V); 269 } 270 271 /// Return whether this instruction can safely wrap. 272 bool TypePromotion::isSafeWrap(Instruction *I) { 273 // We can support a, potentially, wrapping instruction (I) if: 274 // - It is only used by an unsigned icmp. 275 // - The icmp uses a constant. 276 // - The wrapping value (I) is decreasing, i.e would underflow - wrapping 277 // around zero to become a larger number than before. 278 // - The wrapping instruction (I) also uses a constant. 279 // 280 // We can then use the two constants to calculate whether the result would 281 // wrap in respect to itself in the original bitwidth. If it doesn't wrap, 282 // just underflows the range, the icmp would give the same result whether the 283 // result has been truncated or not. We calculate this by: 284 // - Zero extending both constants, if needed, to 32-bits. 285 // - Take the absolute value of I's constant, adding this to the icmp const. 286 // - Check that this value is not out of range for small type. If it is, it 287 // means that it has underflowed enough to wrap around the icmp constant. 288 // 289 // For example: 290 // 291 // %sub = sub i8 %a, 2 292 // %cmp = icmp ule i8 %sub, 254 293 // 294 // If %a = 0, %sub = -2 == FE == 254 295 // But if this is evalulated as a i32 296 // %sub = -2 == FF FF FF FE == 4294967294 297 // So the unsigned compares (i8 and i32) would not yield the same result. 298 // 299 // Another way to look at it is: 300 // %a - 2 <= 254 301 // %a + 2 <= 254 + 2 302 // %a <= 256 303 // And we can't represent 256 in the i8 format, so we don't support it. 304 // 305 // Whereas: 306 // 307 // %sub i8 %a, 1 308 // %cmp = icmp ule i8 %sub, 254 309 // 310 // If %a = 0, %sub = -1 == FF == 255 311 // As i32: 312 // %sub = -1 == FF FF FF FF == 4294967295 313 // 314 // In this case, the unsigned compare results would be the same and this 315 // would also be true for ult, uge and ugt: 316 // - (255 < 254) == (0xFFFFFFFF < 254) == false 317 // - (255 <= 254) == (0xFFFFFFFF <= 254) == false 318 // - (255 > 254) == (0xFFFFFFFF > 254) == true 319 // - (255 >= 254) == (0xFFFFFFFF >= 254) == true 320 // 321 // To demonstrate why we can't handle increasing values: 322 // 323 // %add = add i8 %a, 2 324 // %cmp = icmp ult i8 %add, 127 325 // 326 // If %a = 254, %add = 256 == (i8 1) 327 // As i32: 328 // %add = 256 329 // 330 // (1 < 127) != (256 < 127) 331 332 unsigned Opc = I->getOpcode(); 333 if (Opc != Instruction::Add && Opc != Instruction::Sub) 334 return false; 335 336 if (!I->hasOneUse() || 337 !isa<ICmpInst>(*I->user_begin()) || 338 !isa<ConstantInt>(I->getOperand(1))) 339 return false; 340 341 ConstantInt *OverflowConst = cast<ConstantInt>(I->getOperand(1)); 342 bool NegImm = OverflowConst->isNegative(); 343 bool IsDecreasing = ((Opc == Instruction::Sub) && !NegImm) || 344 ((Opc == Instruction::Add) && NegImm); 345 if (!IsDecreasing) 346 return false; 347 348 // Don't support an icmp that deals with sign bits. 349 auto *CI = cast<ICmpInst>(*I->user_begin()); 350 if (CI->isSigned() || CI->isEquality()) 351 return false; 352 353 ConstantInt *ICmpConst = nullptr; 354 if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(0))) 355 ICmpConst = Const; 356 else if (auto *Const = dyn_cast<ConstantInt>(CI->getOperand(1))) 357 ICmpConst = Const; 358 else 359 return false; 360 361 // Now check that the result can't wrap on itself. 362 APInt Total = ICmpConst->getValue().getBitWidth() < 32 ? 363 ICmpConst->getValue().zext(32) : ICmpConst->getValue(); 364 365 Total += OverflowConst->getValue().getBitWidth() < 32 ? 366 OverflowConst->getValue().abs().zext(32) : OverflowConst->getValue().abs(); 367 368 APInt Max = APInt::getAllOnes(TypePromotion::TypeSize); 369 370 if (Total.getBitWidth() > Max.getBitWidth()) { 371 if (Total.ugt(Max.zext(Total.getBitWidth()))) 372 return false; 373 } else if (Max.getBitWidth() > Total.getBitWidth()) { 374 if (Total.zext(Max.getBitWidth()).ugt(Max)) 375 return false; 376 } else if (Total.ugt(Max)) 377 return false; 378 379 LLVM_DEBUG(dbgs() << "IR Promotion: Allowing safe overflow for " 380 << *I << "\n"); 381 SafeWrap.push_back(I); 382 return true; 383 } 384 385 bool TypePromotion::shouldPromote(Value *V) { 386 if (!isa<IntegerType>(V->getType()) || isSink(V)) 387 return false; 388 389 if (isSource(V)) 390 return true; 391 392 auto *I = dyn_cast<Instruction>(V); 393 if (!I) 394 return false; 395 396 if (isa<ICmpInst>(I)) 397 return false; 398 399 return true; 400 } 401 402 /// Return whether we can safely mutate V's type to ExtTy without having to be 403 /// concerned with zero extending or truncation. 404 static bool isPromotedResultSafe(Instruction *I) { 405 if (GenerateSignBits(I)) 406 return false; 407 408 if (!isa<OverflowingBinaryOperator>(I)) 409 return true; 410 411 return I->hasNoUnsignedWrap(); 412 } 413 414 void IRPromoter::ReplaceAllUsersOfWith(Value *From, Value *To) { 415 SmallVector<Instruction*, 4> Users; 416 Instruction *InstTo = dyn_cast<Instruction>(To); 417 bool ReplacedAll = true; 418 419 LLVM_DEBUG(dbgs() << "IR Promotion: Replacing " << *From << " with " << *To 420 << "\n"); 421 422 for (Use &U : From->uses()) { 423 auto *User = cast<Instruction>(U.getUser()); 424 if (InstTo && User->isIdenticalTo(InstTo)) { 425 ReplacedAll = false; 426 continue; 427 } 428 Users.push_back(User); 429 } 430 431 for (auto *U : Users) 432 U->replaceUsesOfWith(From, To); 433 434 if (ReplacedAll) 435 if (auto *I = dyn_cast<Instruction>(From)) 436 InstsToRemove.insert(I); 437 } 438 439 void IRPromoter::PrepareWrappingAdds() { 440 LLVM_DEBUG(dbgs() << "IR Promotion: Prepare wrapping adds.\n"); 441 IRBuilder<> Builder{Ctx}; 442 443 // For adds that safely wrap and use a negative immediate as operand 1, we 444 // create an equivalent instruction using a positive immediate. 445 // That positive immediate can then be zext along with all the other 446 // immediates later. 447 for (auto *I : SafeWrap) { 448 if (I->getOpcode() != Instruction::Add) 449 continue; 450 451 LLVM_DEBUG(dbgs() << "IR Promotion: Adjusting " << *I << "\n"); 452 assert((isa<ConstantInt>(I->getOperand(1)) && 453 cast<ConstantInt>(I->getOperand(1))->isNegative()) && 454 "Wrapping should have a negative immediate as the second operand"); 455 456 auto Const = cast<ConstantInt>(I->getOperand(1)); 457 auto *NewConst = ConstantInt::get(Ctx, Const->getValue().abs()); 458 Builder.SetInsertPoint(I); 459 Value *NewVal = Builder.CreateSub(I->getOperand(0), NewConst); 460 if (auto *NewInst = dyn_cast<Instruction>(NewVal)) { 461 NewInst->copyIRFlags(I); 462 NewInsts.insert(NewInst); 463 } 464 InstsToRemove.insert(I); 465 I->replaceAllUsesWith(NewVal); 466 LLVM_DEBUG(dbgs() << "IR Promotion: New equivalent: " << *NewVal << "\n"); 467 } 468 for (auto *I : NewInsts) 469 Visited.insert(I); 470 } 471 472 void IRPromoter::ExtendSources() { 473 IRBuilder<> Builder{Ctx}; 474 475 auto InsertZExt = [&](Value *V, Instruction *InsertPt) { 476 assert(V->getType() != ExtTy && "zext already extends to i32"); 477 LLVM_DEBUG(dbgs() << "IR Promotion: Inserting ZExt for " << *V << "\n"); 478 Builder.SetInsertPoint(InsertPt); 479 if (auto *I = dyn_cast<Instruction>(V)) 480 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 481 482 Value *ZExt = Builder.CreateZExt(V, ExtTy); 483 if (auto *I = dyn_cast<Instruction>(ZExt)) { 484 if (isa<Argument>(V)) 485 I->moveBefore(InsertPt); 486 else 487 I->moveAfter(InsertPt); 488 NewInsts.insert(I); 489 } 490 491 ReplaceAllUsersOfWith(V, ZExt); 492 }; 493 494 // Now, insert extending instructions between the sources and their users. 495 LLVM_DEBUG(dbgs() << "IR Promotion: Promoting sources:\n"); 496 for (auto V : Sources) { 497 LLVM_DEBUG(dbgs() << " - " << *V << "\n"); 498 if (auto *I = dyn_cast<Instruction>(V)) 499 InsertZExt(I, I); 500 else if (auto *Arg = dyn_cast<Argument>(V)) { 501 BasicBlock &BB = Arg->getParent()->front(); 502 InsertZExt(Arg, &*BB.getFirstInsertionPt()); 503 } else { 504 llvm_unreachable("unhandled source that needs extending"); 505 } 506 Promoted.insert(V); 507 } 508 } 509 510 void IRPromoter::PromoteTree() { 511 LLVM_DEBUG(dbgs() << "IR Promotion: Mutating the tree..\n"); 512 513 // Mutate the types of the instructions within the tree. Here we handle 514 // constant operands. 515 for (auto *V : Visited) { 516 if (Sources.count(V)) 517 continue; 518 519 auto *I = cast<Instruction>(V); 520 if (Sinks.count(I)) 521 continue; 522 523 for (unsigned i = 0, e = I->getNumOperands(); i < e; ++i) { 524 Value *Op = I->getOperand(i); 525 if ((Op->getType() == ExtTy) || !isa<IntegerType>(Op->getType())) 526 continue; 527 528 if (auto *Const = dyn_cast<ConstantInt>(Op)) { 529 Constant *NewConst = ConstantExpr::getZExt(Const, ExtTy); 530 I->setOperand(i, NewConst); 531 } else if (isa<UndefValue>(Op)) 532 I->setOperand(i, UndefValue::get(ExtTy)); 533 } 534 535 // Mutate the result type, unless this is an icmp or switch. 536 if (!isa<ICmpInst>(I) && !isa<SwitchInst>(I)) { 537 I->mutateType(ExtTy); 538 Promoted.insert(I); 539 } 540 } 541 } 542 543 void IRPromoter::TruncateSinks() { 544 LLVM_DEBUG(dbgs() << "IR Promotion: Fixing up the sinks:\n"); 545 546 IRBuilder<> Builder{Ctx}; 547 548 auto InsertTrunc = [&](Value *V, Type *TruncTy) -> Instruction* { 549 if (!isa<Instruction>(V) || !isa<IntegerType>(V->getType())) 550 return nullptr; 551 552 if ((!Promoted.count(V) && !NewInsts.count(V)) || Sources.count(V)) 553 return nullptr; 554 555 LLVM_DEBUG(dbgs() << "IR Promotion: Creating " << *TruncTy << " Trunc for " 556 << *V << "\n"); 557 Builder.SetInsertPoint(cast<Instruction>(V)); 558 auto *Trunc = dyn_cast<Instruction>(Builder.CreateTrunc(V, TruncTy)); 559 if (Trunc) 560 NewInsts.insert(Trunc); 561 return Trunc; 562 }; 563 564 // Fix up any stores or returns that use the results of the promoted 565 // chain. 566 for (auto I : Sinks) { 567 LLVM_DEBUG(dbgs() << "IR Promotion: For Sink: " << *I << "\n"); 568 569 // Handle calls separately as we need to iterate over arg operands. 570 if (auto *Call = dyn_cast<CallInst>(I)) { 571 for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) { 572 Value *Arg = Call->getArgOperand(i); 573 Type *Ty = TruncTysMap[Call][i]; 574 if (Instruction *Trunc = InsertTrunc(Arg, Ty)) { 575 Trunc->moveBefore(Call); 576 Call->setArgOperand(i, Trunc); 577 } 578 } 579 continue; 580 } 581 582 // Special case switches because we need to truncate the condition. 583 if (auto *Switch = dyn_cast<SwitchInst>(I)) { 584 Type *Ty = TruncTysMap[Switch][0]; 585 if (Instruction *Trunc = InsertTrunc(Switch->getCondition(), Ty)) { 586 Trunc->moveBefore(Switch); 587 Switch->setCondition(Trunc); 588 } 589 continue; 590 } 591 592 // Now handle the others. 593 for (unsigned i = 0; i < I->getNumOperands(); ++i) { 594 Type *Ty = TruncTysMap[I][i]; 595 if (Instruction *Trunc = InsertTrunc(I->getOperand(i), Ty)) { 596 Trunc->moveBefore(I); 597 I->setOperand(i, Trunc); 598 } 599 } 600 } 601 } 602 603 void IRPromoter::Cleanup() { 604 LLVM_DEBUG(dbgs() << "IR Promotion: Cleanup..\n"); 605 // Some zexts will now have become redundant, along with their trunc 606 // operands, so remove them 607 for (auto V : Visited) { 608 if (!isa<ZExtInst>(V)) 609 continue; 610 611 auto ZExt = cast<ZExtInst>(V); 612 if (ZExt->getDestTy() != ExtTy) 613 continue; 614 615 Value *Src = ZExt->getOperand(0); 616 if (ZExt->getSrcTy() == ZExt->getDestTy()) { 617 LLVM_DEBUG(dbgs() << "IR Promotion: Removing unnecessary cast: " << *ZExt 618 << "\n"); 619 ReplaceAllUsersOfWith(ZExt, Src); 620 continue; 621 } 622 623 // Unless they produce a value that is narrower than ExtTy, we can 624 // replace the result of the zext with the input of a newly inserted 625 // trunc. 626 if (NewInsts.count(Src) && isa<TruncInst>(Src) && 627 Src->getType() == OrigTy) { 628 auto *Trunc = cast<TruncInst>(Src); 629 assert(Trunc->getOperand(0)->getType() == ExtTy && 630 "expected inserted trunc to be operating on i32"); 631 ReplaceAllUsersOfWith(ZExt, Trunc->getOperand(0)); 632 } 633 } 634 635 for (auto *I : InstsToRemove) { 636 LLVM_DEBUG(dbgs() << "IR Promotion: Removing " << *I << "\n"); 637 I->dropAllReferences(); 638 I->eraseFromParent(); 639 } 640 } 641 642 void IRPromoter::ConvertTruncs() { 643 LLVM_DEBUG(dbgs() << "IR Promotion: Converting truncs..\n"); 644 IRBuilder<> Builder{Ctx}; 645 646 for (auto *V : Visited) { 647 if (!isa<TruncInst>(V) || Sources.count(V)) 648 continue; 649 650 auto *Trunc = cast<TruncInst>(V); 651 Builder.SetInsertPoint(Trunc); 652 IntegerType *SrcTy = cast<IntegerType>(Trunc->getOperand(0)->getType()); 653 IntegerType *DestTy = cast<IntegerType>(TruncTysMap[Trunc][0]); 654 655 unsigned NumBits = DestTy->getScalarSizeInBits(); 656 ConstantInt *Mask = 657 ConstantInt::get(SrcTy, APInt::getMaxValue(NumBits).getZExtValue()); 658 Value *Masked = Builder.CreateAnd(Trunc->getOperand(0), Mask); 659 660 if (auto *I = dyn_cast<Instruction>(Masked)) 661 NewInsts.insert(I); 662 663 ReplaceAllUsersOfWith(Trunc, Masked); 664 } 665 } 666 667 void IRPromoter::Mutate() { 668 LLVM_DEBUG(dbgs() << "IR Promotion: Promoting use-def chains from " 669 << OrigTy->getBitWidth() << " to " << PromotedWidth << "-bits\n"); 670 671 // Cache original types of the values that will likely need truncating 672 for (auto *I : Sinks) { 673 if (auto *Call = dyn_cast<CallInst>(I)) { 674 for (unsigned i = 0; i < Call->getNumArgOperands(); ++i) { 675 Value *Arg = Call->getArgOperand(i); 676 TruncTysMap[Call].push_back(Arg->getType()); 677 } 678 } else if (auto *Switch = dyn_cast<SwitchInst>(I)) 679 TruncTysMap[I].push_back(Switch->getCondition()->getType()); 680 else { 681 for (unsigned i = 0; i < I->getNumOperands(); ++i) 682 TruncTysMap[I].push_back(I->getOperand(i)->getType()); 683 } 684 } 685 for (auto *V : Visited) { 686 if (!isa<TruncInst>(V) || Sources.count(V)) 687 continue; 688 auto *Trunc = cast<TruncInst>(V); 689 TruncTysMap[Trunc].push_back(Trunc->getDestTy()); 690 } 691 692 // Convert adds using negative immediates to equivalent instructions that use 693 // positive constants. 694 PrepareWrappingAdds(); 695 696 // Insert zext instructions between sources and their users. 697 ExtendSources(); 698 699 // Promote visited instructions, mutating their types in place. 700 PromoteTree(); 701 702 // Convert any truncs, that aren't sources, into AND masks. 703 ConvertTruncs(); 704 705 // Insert trunc instructions for use by calls, stores etc... 706 TruncateSinks(); 707 708 // Finally, remove unecessary zexts and truncs, delete old instructions and 709 // clear the data structures. 710 Cleanup(); 711 712 LLVM_DEBUG(dbgs() << "IR Promotion: Mutation complete\n"); 713 } 714 715 /// We disallow booleans to make life easier when dealing with icmps but allow 716 /// any other integer that fits in a scalar register. Void types are accepted 717 /// so we can handle switches. 718 bool TypePromotion::isSupportedType(Value *V) { 719 Type *Ty = V->getType(); 720 721 // Allow voids and pointers, these won't be promoted. 722 if (Ty->isVoidTy() || Ty->isPointerTy()) 723 return true; 724 725 if (!isa<IntegerType>(Ty) || 726 cast<IntegerType>(Ty)->getBitWidth() == 1 || 727 cast<IntegerType>(Ty)->getBitWidth() > RegisterBitWidth) 728 return false; 729 730 return LessOrEqualTypeSize(V); 731 } 732 733 /// We accept most instructions, as well as Arguments and ConstantInsts. We 734 /// Disallow casts other than zext and truncs and only allow calls if their 735 /// return value is zeroext. We don't allow opcodes that can introduce sign 736 /// bits. 737 bool TypePromotion::isSupportedValue(Value *V) { 738 if (auto *I = dyn_cast<Instruction>(V)) { 739 switch (I->getOpcode()) { 740 default: 741 return isa<BinaryOperator>(I) && isSupportedType(I) && 742 !GenerateSignBits(I); 743 case Instruction::GetElementPtr: 744 case Instruction::Store: 745 case Instruction::Br: 746 case Instruction::Switch: 747 return true; 748 case Instruction::PHI: 749 case Instruction::Select: 750 case Instruction::Ret: 751 case Instruction::Load: 752 case Instruction::Trunc: 753 case Instruction::BitCast: 754 return isSupportedType(I); 755 case Instruction::ZExt: 756 return isSupportedType(I->getOperand(0)); 757 case Instruction::ICmp: 758 // Now that we allow small types than TypeSize, only allow icmp of 759 // TypeSize because they will require a trunc to be legalised. 760 // TODO: Allow icmp of smaller types, and calculate at the end 761 // whether the transform would be beneficial. 762 if (isa<PointerType>(I->getOperand(0)->getType())) 763 return true; 764 return EqualTypeSize(I->getOperand(0)); 765 case Instruction::Call: { 766 // Special cases for calls as we need to check for zeroext 767 // TODO We should accept calls even if they don't have zeroext, as they 768 // can still be sinks. 769 auto *Call = cast<CallInst>(I); 770 return isSupportedType(Call) && 771 Call->hasRetAttr(Attribute::AttrKind::ZExt); 772 } 773 } 774 } else if (isa<Constant>(V) && !isa<ConstantExpr>(V)) { 775 return isSupportedType(V); 776 } else if (isa<Argument>(V)) 777 return isSupportedType(V); 778 779 return isa<BasicBlock>(V); 780 } 781 782 /// Check that the type of V would be promoted and that the original type is 783 /// smaller than the targeted promoted type. Check that we're not trying to 784 /// promote something larger than our base 'TypeSize' type. 785 bool TypePromotion::isLegalToPromote(Value *V) { 786 787 auto *I = dyn_cast<Instruction>(V); 788 if (!I) 789 return true; 790 791 if (SafeToPromote.count(I)) 792 return true; 793 794 if (isPromotedResultSafe(I) || isSafeWrap(I)) { 795 SafeToPromote.insert(I); 796 return true; 797 } 798 return false; 799 } 800 801 bool TypePromotion::TryToPromote(Value *V, unsigned PromotedWidth) { 802 Type *OrigTy = V->getType(); 803 TypeSize = OrigTy->getPrimitiveSizeInBits().getFixedSize(); 804 SafeToPromote.clear(); 805 SafeWrap.clear(); 806 807 if (!isSupportedValue(V) || !shouldPromote(V) || !isLegalToPromote(V)) 808 return false; 809 810 LLVM_DEBUG(dbgs() << "IR Promotion: TryToPromote: " << *V << ", from " 811 << TypeSize << " bits to " << PromotedWidth << "\n"); 812 813 SetVector<Value*> WorkList; 814 SetVector<Value*> Sources; 815 SetVector<Instruction*> Sinks; 816 SetVector<Value*> CurrentVisited; 817 WorkList.insert(V); 818 819 // Return true if V was added to the worklist as a supported instruction, 820 // if it was already visited, or if we don't need to explore it (e.g. 821 // pointer values and GEPs), and false otherwise. 822 auto AddLegalInst = [&](Value *V) { 823 if (CurrentVisited.count(V)) 824 return true; 825 826 // Ignore GEPs because they don't need promoting and the constant indices 827 // will prevent the transformation. 828 if (isa<GetElementPtrInst>(V)) 829 return true; 830 831 if (!isSupportedValue(V) || (shouldPromote(V) && !isLegalToPromote(V))) { 832 LLVM_DEBUG(dbgs() << "IR Promotion: Can't handle: " << *V << "\n"); 833 return false; 834 } 835 836 WorkList.insert(V); 837 return true; 838 }; 839 840 // Iterate through, and add to, a tree of operands and users in the use-def. 841 while (!WorkList.empty()) { 842 Value *V = WorkList.pop_back_val(); 843 if (CurrentVisited.count(V)) 844 continue; 845 846 // Ignore non-instructions, other than arguments. 847 if (!isa<Instruction>(V) && !isSource(V)) 848 continue; 849 850 // If we've already visited this value from somewhere, bail now because 851 // the tree has already been explored. 852 // TODO: This could limit the transform, ie if we try to promote something 853 // from an i8 and fail first, before trying an i16. 854 if (AllVisited.count(V)) 855 return false; 856 857 CurrentVisited.insert(V); 858 AllVisited.insert(V); 859 860 // Calls can be both sources and sinks. 861 if (isSink(V)) 862 Sinks.insert(cast<Instruction>(V)); 863 864 if (isSource(V)) 865 Sources.insert(V); 866 867 if (!isSink(V) && !isSource(V)) { 868 if (auto *I = dyn_cast<Instruction>(V)) { 869 // Visit operands of any instruction visited. 870 for (auto &U : I->operands()) { 871 if (!AddLegalInst(U)) 872 return false; 873 } 874 } 875 } 876 877 // Don't visit users of a node which isn't going to be mutated unless its a 878 // source. 879 if (isSource(V) || shouldPromote(V)) { 880 for (Use &U : V->uses()) { 881 if (!AddLegalInst(U.getUser())) 882 return false; 883 } 884 } 885 } 886 887 LLVM_DEBUG(dbgs() << "IR Promotion: Visited nodes:\n"; 888 for (auto *I : CurrentVisited) 889 I->dump(); 890 ); 891 892 unsigned ToPromote = 0; 893 unsigned NonFreeArgs = 0; 894 SmallPtrSet<BasicBlock*, 4> Blocks; 895 for (auto *V : CurrentVisited) { 896 if (auto *I = dyn_cast<Instruction>(V)) 897 Blocks.insert(I->getParent()); 898 899 if (Sources.count(V)) { 900 if (auto *Arg = dyn_cast<Argument>(V)) 901 if (!Arg->hasZExtAttr() && !Arg->hasSExtAttr()) 902 ++NonFreeArgs; 903 continue; 904 } 905 906 if (Sinks.count(cast<Instruction>(V))) 907 continue; 908 ++ToPromote; 909 } 910 911 // DAG optimizations should be able to handle these cases better, especially 912 // for function arguments. 913 if (ToPromote < 2 || (Blocks.size() == 1 && (NonFreeArgs > SafeWrap.size()))) 914 return false; 915 916 IRPromoter Promoter(*Ctx, cast<IntegerType>(OrigTy), PromotedWidth, 917 CurrentVisited, Sources, Sinks, SafeWrap); 918 Promoter.Mutate(); 919 return true; 920 } 921 922 bool TypePromotion::runOnFunction(Function &F) { 923 if (skipFunction(F) || DisablePromotion) 924 return false; 925 926 LLVM_DEBUG(dbgs() << "IR Promotion: Running on " << F.getName() << "\n"); 927 928 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>(); 929 if (!TPC) 930 return false; 931 932 AllVisited.clear(); 933 SafeToPromote.clear(); 934 SafeWrap.clear(); 935 bool MadeChange = false; 936 const DataLayout &DL = F.getParent()->getDataLayout(); 937 const TargetMachine &TM = TPC->getTM<TargetMachine>(); 938 const TargetSubtargetInfo *SubtargetInfo = TM.getSubtargetImpl(F); 939 const TargetLowering *TLI = SubtargetInfo->getTargetLowering(); 940 const TargetTransformInfo &TII = 941 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 942 RegisterBitWidth = 943 TII.getRegisterBitWidth(TargetTransformInfo::RGK_Scalar).getFixedSize(); 944 Ctx = &F.getParent()->getContext(); 945 946 // Search up from icmps to try to promote their operands. 947 for (BasicBlock &BB : F) { 948 for (auto &I : BB) { 949 if (AllVisited.count(&I)) 950 continue; 951 952 if (!isa<ICmpInst>(&I)) 953 continue; 954 955 auto *ICmp = cast<ICmpInst>(&I); 956 // Skip signed or pointer compares 957 if (ICmp->isSigned() || 958 !isa<IntegerType>(ICmp->getOperand(0)->getType())) 959 continue; 960 961 LLVM_DEBUG(dbgs() << "IR Promotion: Searching from: " << *ICmp << "\n"); 962 963 for (auto &Op : ICmp->operands()) { 964 if (auto *I = dyn_cast<Instruction>(Op)) { 965 EVT SrcVT = TLI->getValueType(DL, I->getType()); 966 if (SrcVT.isSimple() && TLI->isTypeLegal(SrcVT.getSimpleVT())) 967 break; 968 969 if (TLI->getTypeAction(ICmp->getContext(), SrcVT) != 970 TargetLowering::TypePromoteInteger) 971 break; 972 EVT PromotedVT = TLI->getTypeToTransformTo(ICmp->getContext(), SrcVT); 973 if (RegisterBitWidth < PromotedVT.getFixedSizeInBits()) { 974 LLVM_DEBUG(dbgs() << "IR Promotion: Couldn't find target register " 975 << "for promoted type\n"); 976 break; 977 } 978 979 MadeChange |= TryToPromote(I, PromotedVT.getFixedSizeInBits()); 980 break; 981 } 982 } 983 } 984 LLVM_DEBUG(if (verifyFunction(F, &dbgs())) { 985 dbgs() << F; 986 report_fatal_error("Broken function after type promotion"); 987 }); 988 } 989 if (MadeChange) 990 LLVM_DEBUG(dbgs() << "After TypePromotion: " << F << "\n"); 991 992 AllVisited.clear(); 993 SafeToPromote.clear(); 994 SafeWrap.clear(); 995 996 return MadeChange; 997 } 998 999 INITIALIZE_PASS_BEGIN(TypePromotion, DEBUG_TYPE, PASS_NAME, false, false) 1000 INITIALIZE_PASS_END(TypePromotion, DEBUG_TYPE, PASS_NAME, false, false) 1001 1002 char TypePromotion::ID = 0; 1003 1004 FunctionPass *llvm::createTypePromotionPass() { 1005 return new TypePromotion(); 1006 } 1007