1 //===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the auto-upgrade helper functions 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/IR/AutoUpgrade.h" 15 #include "llvm/IR/CFG.h" 16 #include "llvm/IR/CallSite.h" 17 #include "llvm/IR/Constants.h" 18 #include "llvm/IR/DebugInfo.h" 19 #include "llvm/IR/DiagnosticInfo.h" 20 #include "llvm/IR/Function.h" 21 #include "llvm/IR/IRBuilder.h" 22 #include "llvm/IR/Instruction.h" 23 #include "llvm/IR/IntrinsicInst.h" 24 #include "llvm/IR/LLVMContext.h" 25 #include "llvm/IR/Module.h" 26 #include "llvm/Support/ErrorHandling.h" 27 #include <cstring> 28 using namespace llvm; 29 30 // Upgrade the declarations of the SSE4.1 functions whose arguments have 31 // changed their type from v4f32 to v2i64. 32 static bool UpgradeSSE41Function(Function* F, Intrinsic::ID IID, 33 Function *&NewFn) { 34 // Check whether this is an old version of the function, which received 35 // v4f32 arguments. 36 Type *Arg0Type = F->getFunctionType()->getParamType(0); 37 if (Arg0Type != VectorType::get(Type::getFloatTy(F->getContext()), 4)) 38 return false; 39 40 // Yes, it's old, replace it with new version. 41 F->setName(F->getName() + ".old"); 42 NewFn = Intrinsic::getDeclaration(F->getParent(), IID); 43 return true; 44 } 45 46 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) { 47 assert(F && "Illegal to upgrade a non-existent Function."); 48 49 // Quickly eliminate it, if it's not a candidate. 50 StringRef Name = F->getName(); 51 if (Name.size() <= 8 || !Name.startswith("llvm.")) 52 return false; 53 Name = Name.substr(5); // Strip off "llvm." 54 55 switch (Name[0]) { 56 default: break; 57 case 'a': { 58 if (Name.startswith("arm.neon.vclz")) { 59 Type* args[2] = { 60 F->arg_begin()->getType(), 61 Type::getInt1Ty(F->getContext()) 62 }; 63 // Can't use Intrinsic::getDeclaration here as it adds a ".i1" to 64 // the end of the name. Change name from llvm.arm.neon.vclz.* to 65 // llvm.ctlz.* 66 FunctionType* fType = FunctionType::get(F->getReturnType(), args, false); 67 NewFn = Function::Create(fType, F->getLinkage(), 68 "llvm.ctlz." + Name.substr(14), F->getParent()); 69 return true; 70 } 71 if (Name.startswith("arm.neon.vcnt")) { 72 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop, 73 F->arg_begin()->getType()); 74 return true; 75 } 76 break; 77 } 78 case 'c': { 79 if (Name.startswith("ctlz.") && F->arg_size() == 1) { 80 F->setName(Name + ".old"); 81 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz, 82 F->arg_begin()->getType()); 83 return true; 84 } 85 if (Name.startswith("cttz.") && F->arg_size() == 1) { 86 F->setName(Name + ".old"); 87 NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz, 88 F->arg_begin()->getType()); 89 return true; 90 } 91 break; 92 } 93 case 'o': 94 // We only need to change the name to match the mangling including the 95 // address space. 96 if (F->arg_size() == 2 && Name.startswith("objectsize.")) { 97 Type *Tys[2] = { F->getReturnType(), F->arg_begin()->getType() }; 98 if (F->getName() != Intrinsic::getName(Intrinsic::objectsize, Tys)) { 99 F->setName(Name + ".old"); 100 NewFn = Intrinsic::getDeclaration(F->getParent(), 101 Intrinsic::objectsize, Tys); 102 return true; 103 } 104 } 105 break; 106 107 case 'x': { 108 if (Name.startswith("x86.sse2.pcmpeq.") || 109 Name.startswith("x86.sse2.pcmpgt.") || 110 Name.startswith("x86.avx2.pcmpeq.") || 111 Name.startswith("x86.avx2.pcmpgt.") || 112 Name.startswith("x86.avx.vpermil.") || 113 Name == "x86.avx.movnt.dq.256" || 114 Name == "x86.avx.movnt.pd.256" || 115 Name == "x86.avx.movnt.ps.256" || 116 Name == "x86.sse42.crc32.64.8" || 117 (Name.startswith("x86.xop.vpcom") && F->arg_size() == 2)) { 118 NewFn = nullptr; 119 return true; 120 } 121 // SSE4.1 ptest functions may have an old signature. 122 if (Name.startswith("x86.sse41.ptest")) { 123 if (Name == "x86.sse41.ptestc") 124 return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestc, NewFn); 125 if (Name == "x86.sse41.ptestz") 126 return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestz, NewFn); 127 if (Name == "x86.sse41.ptestnzc") 128 return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestnzc, NewFn); 129 } 130 // frcz.ss/sd may need to have an argument dropped 131 if (Name.startswith("x86.xop.vfrcz.ss") && F->arg_size() == 2) { 132 F->setName(Name + ".old"); 133 NewFn = Intrinsic::getDeclaration(F->getParent(), 134 Intrinsic::x86_xop_vfrcz_ss); 135 return true; 136 } 137 if (Name.startswith("x86.xop.vfrcz.sd") && F->arg_size() == 2) { 138 F->setName(Name + ".old"); 139 NewFn = Intrinsic::getDeclaration(F->getParent(), 140 Intrinsic::x86_xop_vfrcz_sd); 141 return true; 142 } 143 // Fix the FMA4 intrinsics to remove the 4 144 if (Name.startswith("x86.fma4.")) { 145 F->setName("llvm.x86.fma" + Name.substr(8)); 146 NewFn = F; 147 return true; 148 } 149 break; 150 } 151 } 152 153 // This may not belong here. This function is effectively being overloaded 154 // to both detect an intrinsic which needs upgrading, and to provide the 155 // upgraded form of the intrinsic. We should perhaps have two separate 156 // functions for this. 157 return false; 158 } 159 160 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) { 161 NewFn = nullptr; 162 bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn); 163 164 // Upgrade intrinsic attributes. This does not change the function. 165 if (NewFn) 166 F = NewFn; 167 if (unsigned id = F->getIntrinsicID()) 168 F->setAttributes(Intrinsic::getAttributes(F->getContext(), 169 (Intrinsic::ID)id)); 170 return Upgraded; 171 } 172 173 static bool UpgradeGlobalStructors(GlobalVariable *GV) { 174 ArrayType *ATy = dyn_cast<ArrayType>(GV->getType()->getElementType()); 175 StructType *OldTy = 176 ATy ? dyn_cast<StructType>(ATy->getElementType()) : nullptr; 177 178 // Only upgrade an array of a two field struct with the appropriate field 179 // types. 180 if (!OldTy || OldTy->getNumElements() != 2) 181 return false; 182 183 // Get the upgraded 3 element type. 184 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo(); 185 Type *Tys[3] = { 186 OldTy->getElementType(0), 187 OldTy->getElementType(1), 188 VoidPtrTy 189 }; 190 StructType *NewTy = 191 StructType::get(GV->getContext(), Tys, /*isPacked=*/false); 192 193 // Build new constants with a null third field filled in. 194 Constant *OldInitC = GV->getInitializer(); 195 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC); 196 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC)) 197 return false; 198 std::vector<Constant *> Initializers; 199 if (OldInit) { 200 for (Use &U : OldInit->operands()) { 201 ConstantStruct *Init = cast<ConstantStruct>(&U); 202 Constant *NewInit = 203 ConstantStruct::get(NewTy, Init->getOperand(0), Init->getOperand(1), 204 Constant::getNullValue(VoidPtrTy), nullptr); 205 Initializers.push_back(NewInit); 206 } 207 } 208 assert(Initializers.size() == ATy->getNumElements()); 209 210 // Replace the old GV with a new one. 211 ATy = ArrayType::get(NewTy, Initializers.size()); 212 Constant *NewInit = ConstantArray::get(ATy, Initializers); 213 GlobalVariable *NewGV = new GlobalVariable( 214 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "", 215 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(), 216 GV->isExternallyInitialized()); 217 NewGV->copyAttributesFrom(GV); 218 NewGV->takeName(GV); 219 assert(GV->use_empty() && "program cannot use initializer list"); 220 GV->eraseFromParent(); 221 return true; 222 } 223 224 bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) { 225 if (GV->getName() == "llvm.global_ctors" || 226 GV->getName() == "llvm.global_dtors") 227 return UpgradeGlobalStructors(GV); 228 229 // Nothing to do yet. 230 return false; 231 } 232 233 // UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the 234 // upgraded intrinsic. All argument and return casting must be provided in 235 // order to seamlessly integrate with existing context. 236 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) { 237 Function *F = CI->getCalledFunction(); 238 LLVMContext &C = CI->getContext(); 239 IRBuilder<> Builder(C); 240 Builder.SetInsertPoint(CI->getParent(), CI); 241 242 assert(F && "Intrinsic call is not direct?"); 243 244 if (!NewFn) { 245 // Get the Function's name. 246 StringRef Name = F->getName(); 247 248 Value *Rep; 249 // Upgrade packed integer vector compares intrinsics to compare instructions 250 if (Name.startswith("llvm.x86.sse2.pcmpeq.") || 251 Name.startswith("llvm.x86.avx2.pcmpeq.")) { 252 Rep = Builder.CreateICmpEQ(CI->getArgOperand(0), CI->getArgOperand(1), 253 "pcmpeq"); 254 // need to sign extend since icmp returns vector of i1 255 Rep = Builder.CreateSExt(Rep, CI->getType(), ""); 256 } else if (Name.startswith("llvm.x86.sse2.pcmpgt.") || 257 Name.startswith("llvm.x86.avx2.pcmpgt.")) { 258 Rep = Builder.CreateICmpSGT(CI->getArgOperand(0), CI->getArgOperand(1), 259 "pcmpgt"); 260 // need to sign extend since icmp returns vector of i1 261 Rep = Builder.CreateSExt(Rep, CI->getType(), ""); 262 } else if (Name == "llvm.x86.avx.movnt.dq.256" || 263 Name == "llvm.x86.avx.movnt.ps.256" || 264 Name == "llvm.x86.avx.movnt.pd.256") { 265 IRBuilder<> Builder(C); 266 Builder.SetInsertPoint(CI->getParent(), CI); 267 268 Module *M = F->getParent(); 269 SmallVector<Value *, 1> Elts; 270 Elts.push_back(ConstantInt::get(Type::getInt32Ty(C), 1)); 271 MDNode *Node = MDNode::get(C, Elts); 272 273 Value *Arg0 = CI->getArgOperand(0); 274 Value *Arg1 = CI->getArgOperand(1); 275 276 // Convert the type of the pointer to a pointer to the stored type. 277 Value *BC = Builder.CreateBitCast(Arg0, 278 PointerType::getUnqual(Arg1->getType()), 279 "cast"); 280 StoreInst *SI = Builder.CreateStore(Arg1, BC); 281 SI->setMetadata(M->getMDKindID("nontemporal"), Node); 282 SI->setAlignment(16); 283 284 // Remove intrinsic. 285 CI->eraseFromParent(); 286 return; 287 } else if (Name.startswith("llvm.x86.xop.vpcom")) { 288 Intrinsic::ID intID; 289 if (Name.endswith("ub")) 290 intID = Intrinsic::x86_xop_vpcomub; 291 else if (Name.endswith("uw")) 292 intID = Intrinsic::x86_xop_vpcomuw; 293 else if (Name.endswith("ud")) 294 intID = Intrinsic::x86_xop_vpcomud; 295 else if (Name.endswith("uq")) 296 intID = Intrinsic::x86_xop_vpcomuq; 297 else if (Name.endswith("b")) 298 intID = Intrinsic::x86_xop_vpcomb; 299 else if (Name.endswith("w")) 300 intID = Intrinsic::x86_xop_vpcomw; 301 else if (Name.endswith("d")) 302 intID = Intrinsic::x86_xop_vpcomd; 303 else if (Name.endswith("q")) 304 intID = Intrinsic::x86_xop_vpcomq; 305 else 306 llvm_unreachable("Unknown suffix"); 307 308 Name = Name.substr(18); // strip off "llvm.x86.xop.vpcom" 309 unsigned Imm; 310 if (Name.startswith("lt")) 311 Imm = 0; 312 else if (Name.startswith("le")) 313 Imm = 1; 314 else if (Name.startswith("gt")) 315 Imm = 2; 316 else if (Name.startswith("ge")) 317 Imm = 3; 318 else if (Name.startswith("eq")) 319 Imm = 4; 320 else if (Name.startswith("ne")) 321 Imm = 5; 322 else if (Name.startswith("true")) 323 Imm = 6; 324 else if (Name.startswith("false")) 325 Imm = 7; 326 else 327 llvm_unreachable("Unknown condition"); 328 329 Function *VPCOM = Intrinsic::getDeclaration(F->getParent(), intID); 330 Rep = Builder.CreateCall3(VPCOM, CI->getArgOperand(0), 331 CI->getArgOperand(1), Builder.getInt8(Imm)); 332 } else if (Name == "llvm.x86.sse42.crc32.64.8") { 333 Function *CRC32 = Intrinsic::getDeclaration(F->getParent(), 334 Intrinsic::x86_sse42_crc32_32_8); 335 Value *Trunc0 = Builder.CreateTrunc(CI->getArgOperand(0), Type::getInt32Ty(C)); 336 Rep = Builder.CreateCall2(CRC32, Trunc0, CI->getArgOperand(1)); 337 Rep = Builder.CreateZExt(Rep, CI->getType(), ""); 338 } else { 339 bool PD128 = false, PD256 = false, PS128 = false, PS256 = false; 340 if (Name == "llvm.x86.avx.vpermil.pd.256") 341 PD256 = true; 342 else if (Name == "llvm.x86.avx.vpermil.pd") 343 PD128 = true; 344 else if (Name == "llvm.x86.avx.vpermil.ps.256") 345 PS256 = true; 346 else if (Name == "llvm.x86.avx.vpermil.ps") 347 PS128 = true; 348 349 if (PD256 || PD128 || PS256 || PS128) { 350 Value *Op0 = CI->getArgOperand(0); 351 unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue(); 352 SmallVector<Constant*, 8> Idxs; 353 354 if (PD128) 355 for (unsigned i = 0; i != 2; ++i) 356 Idxs.push_back(Builder.getInt32((Imm >> i) & 0x1)); 357 else if (PD256) 358 for (unsigned l = 0; l != 4; l+=2) 359 for (unsigned i = 0; i != 2; ++i) 360 Idxs.push_back(Builder.getInt32(((Imm >> (l+i)) & 0x1) + l)); 361 else if (PS128) 362 for (unsigned i = 0; i != 4; ++i) 363 Idxs.push_back(Builder.getInt32((Imm >> (2 * i)) & 0x3)); 364 else if (PS256) 365 for (unsigned l = 0; l != 8; l+=4) 366 for (unsigned i = 0; i != 4; ++i) 367 Idxs.push_back(Builder.getInt32(((Imm >> (2 * i)) & 0x3) + l)); 368 else 369 llvm_unreachable("Unexpected function"); 370 371 Rep = Builder.CreateShuffleVector(Op0, Op0, ConstantVector::get(Idxs)); 372 } else { 373 llvm_unreachable("Unknown function for CallInst upgrade."); 374 } 375 } 376 377 CI->replaceAllUsesWith(Rep); 378 CI->eraseFromParent(); 379 return; 380 } 381 382 std::string Name = CI->getName().str(); 383 CI->setName(Name + ".old"); 384 385 switch (NewFn->getIntrinsicID()) { 386 default: 387 llvm_unreachable("Unknown function for CallInst upgrade."); 388 389 case Intrinsic::ctlz: 390 case Intrinsic::cttz: 391 assert(CI->getNumArgOperands() == 1 && 392 "Mismatch between function args and call args"); 393 CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0), 394 Builder.getFalse(), Name)); 395 CI->eraseFromParent(); 396 return; 397 398 case Intrinsic::objectsize: 399 CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, 400 CI->getArgOperand(0), 401 CI->getArgOperand(1), 402 Name)); 403 CI->eraseFromParent(); 404 return; 405 406 case Intrinsic::arm_neon_vclz: { 407 // Change name from llvm.arm.neon.vclz.* to llvm.ctlz.* 408 CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0), 409 Builder.getFalse(), 410 "llvm.ctlz." + Name.substr(14))); 411 CI->eraseFromParent(); 412 return; 413 } 414 case Intrinsic::ctpop: { 415 CI->replaceAllUsesWith(Builder.CreateCall(NewFn, CI->getArgOperand(0))); 416 CI->eraseFromParent(); 417 return; 418 } 419 420 case Intrinsic::x86_xop_vfrcz_ss: 421 case Intrinsic::x86_xop_vfrcz_sd: 422 CI->replaceAllUsesWith(Builder.CreateCall(NewFn, CI->getArgOperand(1), 423 Name)); 424 CI->eraseFromParent(); 425 return; 426 427 case Intrinsic::x86_sse41_ptestc: 428 case Intrinsic::x86_sse41_ptestz: 429 case Intrinsic::x86_sse41_ptestnzc: { 430 // The arguments for these intrinsics used to be v4f32, and changed 431 // to v2i64. This is purely a nop, since those are bitwise intrinsics. 432 // So, the only thing required is a bitcast for both arguments. 433 // First, check the arguments have the old type. 434 Value *Arg0 = CI->getArgOperand(0); 435 if (Arg0->getType() != VectorType::get(Type::getFloatTy(C), 4)) 436 return; 437 438 // Old intrinsic, add bitcasts 439 Value *Arg1 = CI->getArgOperand(1); 440 441 Value *BC0 = 442 Builder.CreateBitCast(Arg0, 443 VectorType::get(Type::getInt64Ty(C), 2), 444 "cast"); 445 Value *BC1 = 446 Builder.CreateBitCast(Arg1, 447 VectorType::get(Type::getInt64Ty(C), 2), 448 "cast"); 449 450 CallInst* NewCall = Builder.CreateCall2(NewFn, BC0, BC1, Name); 451 CI->replaceAllUsesWith(NewCall); 452 CI->eraseFromParent(); 453 return; 454 } 455 } 456 } 457 458 // This tests each Function to determine if it needs upgrading. When we find 459 // one we are interested in, we then upgrade all calls to reflect the new 460 // function. 461 void llvm::UpgradeCallsToIntrinsic(Function* F) { 462 assert(F && "Illegal attempt to upgrade a non-existent intrinsic."); 463 464 // Upgrade the function and check if it is a totaly new function. 465 Function *NewFn; 466 if (UpgradeIntrinsicFunction(F, NewFn)) { 467 if (NewFn != F) { 468 // Replace all uses to the old function with the new one if necessary. 469 for (Value::user_iterator UI = F->user_begin(), UE = F->user_end(); 470 UI != UE; ) { 471 if (CallInst *CI = dyn_cast<CallInst>(*UI++)) 472 UpgradeIntrinsicCall(CI, NewFn); 473 } 474 // Remove old function, no longer used, from the module. 475 F->eraseFromParent(); 476 } 477 } 478 } 479 480 void llvm::UpgradeInstWithTBAATag(Instruction *I) { 481 MDNode *MD = I->getMetadata(LLVMContext::MD_tbaa); 482 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag"); 483 // Check if the tag uses struct-path aware TBAA format. 484 if (isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3) 485 return; 486 487 if (MD->getNumOperands() == 3) { 488 Value *Elts[] = { 489 MD->getOperand(0), 490 MD->getOperand(1) 491 }; 492 MDNode *ScalarType = MDNode::get(I->getContext(), Elts); 493 // Create a MDNode <ScalarType, ScalarType, offset 0, const> 494 Value *Elts2[] = { 495 ScalarType, ScalarType, 496 Constant::getNullValue(Type::getInt64Ty(I->getContext())), 497 MD->getOperand(2) 498 }; 499 I->setMetadata(LLVMContext::MD_tbaa, MDNode::get(I->getContext(), Elts2)); 500 } else { 501 // Create a MDNode <MD, MD, offset 0> 502 Value *Elts[] = {MD, MD, 503 Constant::getNullValue(Type::getInt64Ty(I->getContext()))}; 504 I->setMetadata(LLVMContext::MD_tbaa, MDNode::get(I->getContext(), Elts)); 505 } 506 } 507 508 Instruction *llvm::UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy, 509 Instruction *&Temp) { 510 if (Opc != Instruction::BitCast) 511 return nullptr; 512 513 Temp = nullptr; 514 Type *SrcTy = V->getType(); 515 if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() && 516 SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) { 517 LLVMContext &Context = V->getContext(); 518 519 // We have no information about target data layout, so we assume that 520 // the maximum pointer size is 64bit. 521 Type *MidTy = Type::getInt64Ty(Context); 522 Temp = CastInst::Create(Instruction::PtrToInt, V, MidTy); 523 524 return CastInst::Create(Instruction::IntToPtr, Temp, DestTy); 525 } 526 527 return nullptr; 528 } 529 530 Value *llvm::UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy) { 531 if (Opc != Instruction::BitCast) 532 return nullptr; 533 534 Type *SrcTy = C->getType(); 535 if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() && 536 SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) { 537 LLVMContext &Context = C->getContext(); 538 539 // We have no information about target data layout, so we assume that 540 // the maximum pointer size is 64bit. 541 Type *MidTy = Type::getInt64Ty(Context); 542 543 return ConstantExpr::getIntToPtr(ConstantExpr::getPtrToInt(C, MidTy), 544 DestTy); 545 } 546 547 return nullptr; 548 } 549 550 /// Check the debug info version number, if it is out-dated, drop the debug 551 /// info. Return true if module is modified. 552 bool llvm::UpgradeDebugInfo(Module &M) { 553 unsigned Version = getDebugMetadataVersionFromModule(M); 554 if (Version == DEBUG_METADATA_VERSION) 555 return false; 556 557 bool RetCode = StripDebugInfo(M); 558 if (RetCode) { 559 DiagnosticInfoDebugMetadataVersion DiagVersion(M, Version); 560 M.getContext().diagnose(DiagVersion); 561 } 562 return RetCode; 563 } 564