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