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