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