1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===// 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 all of the non-inline methods for the LLVM instruction 11 // classes. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/IR/Instructions.h" 16 #include "LLVMContextImpl.h" 17 #include "llvm/IR/CallSite.h" 18 #include "llvm/IR/ConstantRange.h" 19 #include "llvm/IR/Constants.h" 20 #include "llvm/IR/DataLayout.h" 21 #include "llvm/IR/DerivedTypes.h" 22 #include "llvm/IR/Function.h" 23 #include "llvm/IR/Module.h" 24 #include "llvm/IR/Operator.h" 25 #include "llvm/Support/ErrorHandling.h" 26 #include "llvm/Support/MathExtras.h" 27 using namespace llvm; 28 29 //===----------------------------------------------------------------------===// 30 // CallSite Class 31 //===----------------------------------------------------------------------===// 32 33 User::op_iterator CallSite::getCallee() const { 34 Instruction *II(getInstruction()); 35 return isCall() 36 ? cast<CallInst>(II)->op_end() - 1 // Skip Callee 37 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee 38 } 39 40 //===----------------------------------------------------------------------===// 41 // TerminatorInst Class 42 //===----------------------------------------------------------------------===// 43 44 // Out of line virtual method, so the vtable, etc has a home. 45 TerminatorInst::~TerminatorInst() { 46 } 47 48 //===----------------------------------------------------------------------===// 49 // UnaryInstruction Class 50 //===----------------------------------------------------------------------===// 51 52 // Out of line virtual method, so the vtable, etc has a home. 53 UnaryInstruction::~UnaryInstruction() { 54 } 55 56 //===----------------------------------------------------------------------===// 57 // SelectInst Class 58 //===----------------------------------------------------------------------===// 59 60 /// areInvalidOperands - Return a string if the specified operands are invalid 61 /// for a select operation, otherwise return null. 62 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) { 63 if (Op1->getType() != Op2->getType()) 64 return "both values to select must have same type"; 65 66 if (Op1->getType()->isTokenTy()) 67 return "select values cannot have token type"; 68 69 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) { 70 // Vector select. 71 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext())) 72 return "vector select condition element type must be i1"; 73 VectorType *ET = dyn_cast<VectorType>(Op1->getType()); 74 if (!ET) 75 return "selected values for vector select must be vectors"; 76 if (ET->getNumElements() != VT->getNumElements()) 77 return "vector select requires selected vectors to have " 78 "the same vector length as select condition"; 79 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) { 80 return "select condition must be i1 or <n x i1>"; 81 } 82 return nullptr; 83 } 84 85 86 //===----------------------------------------------------------------------===// 87 // PHINode Class 88 //===----------------------------------------------------------------------===// 89 90 PHINode::PHINode(const PHINode &PN) 91 : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()), 92 ReservedSpace(PN.getNumOperands()) { 93 allocHungoffUses(PN.getNumOperands()); 94 std::copy(PN.op_begin(), PN.op_end(), op_begin()); 95 std::copy(PN.block_begin(), PN.block_end(), block_begin()); 96 SubclassOptionalData = PN.SubclassOptionalData; 97 } 98 99 // removeIncomingValue - Remove an incoming value. This is useful if a 100 // predecessor basic block is deleted. 101 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) { 102 Value *Removed = getIncomingValue(Idx); 103 104 // Move everything after this operand down. 105 // 106 // FIXME: we could just swap with the end of the list, then erase. However, 107 // clients might not expect this to happen. The code as it is thrashes the 108 // use/def lists, which is kinda lame. 109 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx); 110 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx); 111 112 // Nuke the last value. 113 Op<-1>().set(nullptr); 114 setNumHungOffUseOperands(getNumOperands() - 1); 115 116 // If the PHI node is dead, because it has zero entries, nuke it now. 117 if (getNumOperands() == 0 && DeletePHIIfEmpty) { 118 // If anyone is using this PHI, make them use a dummy value instead... 119 replaceAllUsesWith(UndefValue::get(getType())); 120 eraseFromParent(); 121 } 122 return Removed; 123 } 124 125 /// growOperands - grow operands - This grows the operand list in response 126 /// to a push_back style of operation. This grows the number of ops by 1.5 127 /// times. 128 /// 129 void PHINode::growOperands() { 130 unsigned e = getNumOperands(); 131 unsigned NumOps = e + e / 2; 132 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common. 133 134 ReservedSpace = NumOps; 135 growHungoffUses(ReservedSpace, /* IsPhi */ true); 136 } 137 138 /// hasConstantValue - If the specified PHI node always merges together the same 139 /// value, return the value, otherwise return null. 140 Value *PHINode::hasConstantValue() const { 141 // Exploit the fact that phi nodes always have at least one entry. 142 Value *ConstantValue = getIncomingValue(0); 143 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i) 144 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) { 145 if (ConstantValue != this) 146 return nullptr; // Incoming values not all the same. 147 // The case where the first value is this PHI. 148 ConstantValue = getIncomingValue(i); 149 } 150 if (ConstantValue == this) 151 return UndefValue::get(getType()); 152 return ConstantValue; 153 } 154 155 //===----------------------------------------------------------------------===// 156 // LandingPadInst Implementation 157 //===----------------------------------------------------------------------===// 158 159 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, 160 const Twine &NameStr, Instruction *InsertBefore) 161 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) { 162 init(NumReservedValues, NameStr); 163 } 164 165 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, 166 const Twine &NameStr, BasicBlock *InsertAtEnd) 167 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) { 168 init(NumReservedValues, NameStr); 169 } 170 171 LandingPadInst::LandingPadInst(const LandingPadInst &LP) 172 : Instruction(LP.getType(), Instruction::LandingPad, nullptr, 173 LP.getNumOperands()), 174 ReservedSpace(LP.getNumOperands()) { 175 allocHungoffUses(LP.getNumOperands()); 176 Use *OL = getOperandList(); 177 const Use *InOL = LP.getOperandList(); 178 for (unsigned I = 0, E = ReservedSpace; I != E; ++I) 179 OL[I] = InOL[I]; 180 181 setCleanup(LP.isCleanup()); 182 } 183 184 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, 185 const Twine &NameStr, 186 Instruction *InsertBefore) { 187 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore); 188 } 189 190 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, 191 const Twine &NameStr, 192 BasicBlock *InsertAtEnd) { 193 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd); 194 } 195 196 void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) { 197 ReservedSpace = NumReservedValues; 198 setNumHungOffUseOperands(0); 199 allocHungoffUses(ReservedSpace); 200 setName(NameStr); 201 setCleanup(false); 202 } 203 204 /// growOperands - grow operands - This grows the operand list in response to a 205 /// push_back style of operation. This grows the number of ops by 2 times. 206 void LandingPadInst::growOperands(unsigned Size) { 207 unsigned e = getNumOperands(); 208 if (ReservedSpace >= e + Size) return; 209 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2; 210 growHungoffUses(ReservedSpace); 211 } 212 213 void LandingPadInst::addClause(Constant *Val) { 214 unsigned OpNo = getNumOperands(); 215 growOperands(1); 216 assert(OpNo < ReservedSpace && "Growing didn't work!"); 217 setNumHungOffUseOperands(getNumOperands() + 1); 218 getOperandList()[OpNo] = Val; 219 } 220 221 //===----------------------------------------------------------------------===// 222 // CallInst Implementation 223 //===----------------------------------------------------------------------===// 224 225 CallInst::~CallInst() { 226 } 227 228 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args, 229 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) { 230 this->FTy = FTy; 231 assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 && 232 "NumOperands not set up?"); 233 Op<-1>() = Func; 234 235 #ifndef NDEBUG 236 assert((Args.size() == FTy->getNumParams() || 237 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && 238 "Calling a function with bad signature!"); 239 240 for (unsigned i = 0; i != Args.size(); ++i) 241 assert((i >= FTy->getNumParams() || 242 FTy->getParamType(i) == Args[i]->getType()) && 243 "Calling a function with a bad signature!"); 244 #endif 245 246 std::copy(Args.begin(), Args.end(), op_begin()); 247 248 auto It = populateBundleOperandInfos(Bundles, Args.size()); 249 (void)It; 250 assert(It + 1 == op_end() && "Should add up!"); 251 252 setName(NameStr); 253 } 254 255 void CallInst::init(Value *Func, const Twine &NameStr) { 256 FTy = 257 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType()); 258 assert(getNumOperands() == 1 && "NumOperands not set up?"); 259 Op<-1>() = Func; 260 261 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature"); 262 263 setName(NameStr); 264 } 265 266 CallInst::CallInst(Value *Func, const Twine &Name, 267 Instruction *InsertBefore) 268 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType()) 269 ->getElementType())->getReturnType(), 270 Instruction::Call, 271 OperandTraits<CallInst>::op_end(this) - 1, 272 1, InsertBefore) { 273 init(Func, Name); 274 } 275 276 CallInst::CallInst(Value *Func, const Twine &Name, 277 BasicBlock *InsertAtEnd) 278 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType()) 279 ->getElementType())->getReturnType(), 280 Instruction::Call, 281 OperandTraits<CallInst>::op_end(this) - 1, 282 1, InsertAtEnd) { 283 init(Func, Name); 284 } 285 286 CallInst::CallInst(const CallInst &CI) 287 : Instruction(CI.getType(), Instruction::Call, 288 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(), 289 CI.getNumOperands()), 290 AttributeList(CI.AttributeList), FTy(CI.FTy) { 291 setTailCallKind(CI.getTailCallKind()); 292 setCallingConv(CI.getCallingConv()); 293 294 std::copy(CI.op_begin(), CI.op_end(), op_begin()); 295 std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(), 296 bundle_op_info_begin()); 297 SubclassOptionalData = CI.SubclassOptionalData; 298 } 299 300 CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB, 301 Instruction *InsertPt) { 302 CallSite CS(CI); 303 std::vector<Value *> Args(CS.arg_begin(), CS.arg_end()); 304 305 auto *NewCI = CallInst::Create(CI->getCalledValue(), Args, OpB, CI->getName(), 306 InsertPt); 307 NewCI->setTailCallKind(CI->getTailCallKind()); 308 NewCI->setCallingConv(CI->getCallingConv()); 309 NewCI->SubclassOptionalData = CI->SubclassOptionalData; 310 return NewCI; 311 } 312 313 void CallInst::addAttribute(unsigned i, Attribute::AttrKind attr) { 314 AttributeSet PAL = getAttributes(); 315 PAL = PAL.addAttribute(getContext(), i, attr); 316 setAttributes(PAL); 317 } 318 319 void CallInst::addAttribute(unsigned i, StringRef Kind, StringRef Value) { 320 AttributeSet PAL = getAttributes(); 321 PAL = PAL.addAttribute(getContext(), i, Kind, Value); 322 setAttributes(PAL); 323 } 324 325 void CallInst::removeAttribute(unsigned i, Attribute attr) { 326 AttributeSet PAL = getAttributes(); 327 AttrBuilder B(attr); 328 LLVMContext &Context = getContext(); 329 PAL = PAL.removeAttributes(Context, i, 330 AttributeSet::get(Context, i, B)); 331 setAttributes(PAL); 332 } 333 334 void CallInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) { 335 AttributeSet PAL = getAttributes(); 336 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes); 337 setAttributes(PAL); 338 } 339 340 void CallInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) { 341 AttributeSet PAL = getAttributes(); 342 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes); 343 setAttributes(PAL); 344 } 345 346 bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const { 347 assert(i < (getNumArgOperands() + 1) && "Param index out of bounds!"); 348 349 if (AttributeList.hasAttribute(i, A)) 350 return true; 351 if (const Function *F = getCalledFunction()) 352 return F->getAttributes().hasAttribute(i, A); 353 return false; 354 } 355 356 bool CallInst::dataOperandHasImpliedAttr(unsigned i, 357 Attribute::AttrKind A) const { 358 359 // There are getNumOperands() - 1 data operands. The last operand is the 360 // callee. 361 assert(i < getNumOperands() && "Data operand index out of bounds!"); 362 363 // The attribute A can either be directly specified, if the operand in 364 // question is a call argument; or be indirectly implied by the kind of its 365 // containing operand bundle, if the operand is a bundle operand. 366 367 if (i < (getNumArgOperands() + 1)) 368 return paramHasAttr(i, A); 369 370 assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) && 371 "Must be either a call argument or an operand bundle!"); 372 return bundleOperandHasAttr(i - 1, A); 373 } 374 375 /// IsConstantOne - Return true only if val is constant int 1 376 static bool IsConstantOne(Value *val) { 377 assert(val && "IsConstantOne does not work with nullptr val"); 378 const ConstantInt *CVal = dyn_cast<ConstantInt>(val); 379 return CVal && CVal->isOne(); 380 } 381 382 static Instruction *createMalloc(Instruction *InsertBefore, 383 BasicBlock *InsertAtEnd, Type *IntPtrTy, 384 Type *AllocTy, Value *AllocSize, 385 Value *ArraySize, Function *MallocF, 386 const Twine &Name) { 387 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && 388 "createMalloc needs either InsertBefore or InsertAtEnd"); 389 390 // malloc(type) becomes: 391 // bitcast (i8* malloc(typeSize)) to type* 392 // malloc(type, arraySize) becomes: 393 // bitcast (i8 *malloc(typeSize*arraySize)) to type* 394 if (!ArraySize) 395 ArraySize = ConstantInt::get(IntPtrTy, 1); 396 else if (ArraySize->getType() != IntPtrTy) { 397 if (InsertBefore) 398 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false, 399 "", InsertBefore); 400 else 401 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false, 402 "", InsertAtEnd); 403 } 404 405 if (!IsConstantOne(ArraySize)) { 406 if (IsConstantOne(AllocSize)) { 407 AllocSize = ArraySize; // Operand * 1 = Operand 408 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) { 409 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy, 410 false /*ZExt*/); 411 // Malloc arg is constant product of type size and array size 412 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize)); 413 } else { 414 // Multiply type size by the array size... 415 if (InsertBefore) 416 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, 417 "mallocsize", InsertBefore); 418 else 419 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, 420 "mallocsize", InsertAtEnd); 421 } 422 } 423 424 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size"); 425 // Create the call to Malloc. 426 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; 427 Module* M = BB->getParent()->getParent(); 428 Type *BPTy = Type::getInt8PtrTy(BB->getContext()); 429 Value *MallocFunc = MallocF; 430 if (!MallocFunc) 431 // prototype malloc as "void *malloc(size_t)" 432 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, nullptr); 433 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy); 434 CallInst *MCall = nullptr; 435 Instruction *Result = nullptr; 436 if (InsertBefore) { 437 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore); 438 Result = MCall; 439 if (Result->getType() != AllocPtrType) 440 // Create a cast instruction to convert to the right type... 441 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore); 442 } else { 443 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall"); 444 Result = MCall; 445 if (Result->getType() != AllocPtrType) { 446 InsertAtEnd->getInstList().push_back(MCall); 447 // Create a cast instruction to convert to the right type... 448 Result = new BitCastInst(MCall, AllocPtrType, Name); 449 } 450 } 451 MCall->setTailCall(); 452 if (Function *F = dyn_cast<Function>(MallocFunc)) { 453 MCall->setCallingConv(F->getCallingConv()); 454 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0); 455 } 456 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type"); 457 458 return Result; 459 } 460 461 /// CreateMalloc - Generate the IR for a call to malloc: 462 /// 1. Compute the malloc call's argument as the specified type's size, 463 /// possibly multiplied by the array size if the array size is not 464 /// constant 1. 465 /// 2. Call malloc with that argument. 466 /// 3. Bitcast the result of the malloc call to the specified type. 467 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore, 468 Type *IntPtrTy, Type *AllocTy, 469 Value *AllocSize, Value *ArraySize, 470 Function * MallocF, 471 const Twine &Name) { 472 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize, 473 ArraySize, MallocF, Name); 474 } 475 476 /// CreateMalloc - Generate the IR for a call to malloc: 477 /// 1. Compute the malloc call's argument as the specified type's size, 478 /// possibly multiplied by the array size if the array size is not 479 /// constant 1. 480 /// 2. Call malloc with that argument. 481 /// 3. Bitcast the result of the malloc call to the specified type. 482 /// Note: This function does not add the bitcast to the basic block, that is the 483 /// responsibility of the caller. 484 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd, 485 Type *IntPtrTy, Type *AllocTy, 486 Value *AllocSize, Value *ArraySize, 487 Function *MallocF, const Twine &Name) { 488 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize, 489 ArraySize, MallocF, Name); 490 } 491 492 static Instruction* createFree(Value* Source, Instruction *InsertBefore, 493 BasicBlock *InsertAtEnd) { 494 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && 495 "createFree needs either InsertBefore or InsertAtEnd"); 496 assert(Source->getType()->isPointerTy() && 497 "Can not free something of nonpointer type!"); 498 499 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; 500 Module* M = BB->getParent()->getParent(); 501 502 Type *VoidTy = Type::getVoidTy(M->getContext()); 503 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext()); 504 // prototype free as "void free(void*)" 505 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, nullptr); 506 CallInst* Result = nullptr; 507 Value *PtrCast = Source; 508 if (InsertBefore) { 509 if (Source->getType() != IntPtrTy) 510 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore); 511 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore); 512 } else { 513 if (Source->getType() != IntPtrTy) 514 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd); 515 Result = CallInst::Create(FreeFunc, PtrCast, ""); 516 } 517 Result->setTailCall(); 518 if (Function *F = dyn_cast<Function>(FreeFunc)) 519 Result->setCallingConv(F->getCallingConv()); 520 521 return Result; 522 } 523 524 /// CreateFree - Generate the IR for a call to the builtin free function. 525 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) { 526 return createFree(Source, InsertBefore, nullptr); 527 } 528 529 /// CreateFree - Generate the IR for a call to the builtin free function. 530 /// Note: This function does not add the call to the basic block, that is the 531 /// responsibility of the caller. 532 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) { 533 Instruction* FreeCall = createFree(Source, nullptr, InsertAtEnd); 534 assert(FreeCall && "CreateFree did not create a CallInst"); 535 return FreeCall; 536 } 537 538 //===----------------------------------------------------------------------===// 539 // InvokeInst Implementation 540 //===----------------------------------------------------------------------===// 541 542 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal, 543 BasicBlock *IfException, ArrayRef<Value *> Args, 544 ArrayRef<OperandBundleDef> Bundles, 545 const Twine &NameStr) { 546 this->FTy = FTy; 547 548 assert(getNumOperands() == 3 + Args.size() + CountBundleInputs(Bundles) && 549 "NumOperands not set up?"); 550 Op<-3>() = Fn; 551 Op<-2>() = IfNormal; 552 Op<-1>() = IfException; 553 554 #ifndef NDEBUG 555 assert(((Args.size() == FTy->getNumParams()) || 556 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && 557 "Invoking a function with bad signature"); 558 559 for (unsigned i = 0, e = Args.size(); i != e; i++) 560 assert((i >= FTy->getNumParams() || 561 FTy->getParamType(i) == Args[i]->getType()) && 562 "Invoking a function with a bad signature!"); 563 #endif 564 565 std::copy(Args.begin(), Args.end(), op_begin()); 566 567 auto It = populateBundleOperandInfos(Bundles, Args.size()); 568 (void)It; 569 assert(It + 3 == op_end() && "Should add up!"); 570 571 setName(NameStr); 572 } 573 574 InvokeInst::InvokeInst(const InvokeInst &II) 575 : TerminatorInst(II.getType(), Instruction::Invoke, 576 OperandTraits<InvokeInst>::op_end(this) - 577 II.getNumOperands(), 578 II.getNumOperands()), 579 AttributeList(II.AttributeList), FTy(II.FTy) { 580 setCallingConv(II.getCallingConv()); 581 std::copy(II.op_begin(), II.op_end(), op_begin()); 582 std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(), 583 bundle_op_info_begin()); 584 SubclassOptionalData = II.SubclassOptionalData; 585 } 586 587 InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB, 588 Instruction *InsertPt) { 589 CallSite CS(II); 590 std::vector<Value *> Args(CS.arg_begin(), CS.arg_end()); 591 592 auto *NewII = InvokeInst::Create(II->getCalledValue(), II->getNormalDest(), 593 II->getUnwindDest(), Args, OpB, 594 II->getName(), InsertPt); 595 NewII->setCallingConv(II->getCallingConv()); 596 NewII->SubclassOptionalData = II->SubclassOptionalData; 597 return NewII; 598 } 599 600 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const { 601 return getSuccessor(idx); 602 } 603 unsigned InvokeInst::getNumSuccessorsV() const { 604 return getNumSuccessors(); 605 } 606 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) { 607 return setSuccessor(idx, B); 608 } 609 610 bool InvokeInst::hasFnAttrImpl(Attribute::AttrKind A) const { 611 if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A)) 612 return true; 613 614 // Operand bundles override attributes on the called function, but don't 615 // override attributes directly present on the invoke instruction. 616 if (isFnAttrDisallowedByOpBundle(A)) 617 return false; 618 619 if (const Function *F = getCalledFunction()) 620 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A); 621 return false; 622 } 623 624 bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const { 625 assert(i < (getNumArgOperands() + 1) && "Param index out of bounds!"); 626 627 if (AttributeList.hasAttribute(i, A)) 628 return true; 629 if (const Function *F = getCalledFunction()) 630 return F->getAttributes().hasAttribute(i, A); 631 return false; 632 } 633 634 bool InvokeInst::dataOperandHasImpliedAttr(unsigned i, 635 Attribute::AttrKind A) const { 636 // There are getNumOperands() - 3 data operands. The last three operands are 637 // the callee and the two successor basic blocks. 638 assert(i < (getNumOperands() - 2) && "Data operand index out of bounds!"); 639 640 // The attribute A can either be directly specified, if the operand in 641 // question is an invoke argument; or be indirectly implied by the kind of its 642 // containing operand bundle, if the operand is a bundle operand. 643 644 if (i < (getNumArgOperands() + 1)) 645 return paramHasAttr(i, A); 646 647 assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) && 648 "Must be either an invoke argument or an operand bundle!"); 649 return bundleOperandHasAttr(i - 1, A); 650 } 651 652 void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind attr) { 653 AttributeSet PAL = getAttributes(); 654 PAL = PAL.addAttribute(getContext(), i, attr); 655 setAttributes(PAL); 656 } 657 658 void InvokeInst::removeAttribute(unsigned i, Attribute attr) { 659 AttributeSet PAL = getAttributes(); 660 AttrBuilder B(attr); 661 PAL = PAL.removeAttributes(getContext(), i, 662 AttributeSet::get(getContext(), i, B)); 663 setAttributes(PAL); 664 } 665 666 void InvokeInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) { 667 AttributeSet PAL = getAttributes(); 668 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes); 669 setAttributes(PAL); 670 } 671 672 void InvokeInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) { 673 AttributeSet PAL = getAttributes(); 674 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes); 675 setAttributes(PAL); 676 } 677 678 LandingPadInst *InvokeInst::getLandingPadInst() const { 679 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI()); 680 } 681 682 //===----------------------------------------------------------------------===// 683 // ReturnInst Implementation 684 //===----------------------------------------------------------------------===// 685 686 ReturnInst::ReturnInst(const ReturnInst &RI) 687 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret, 688 OperandTraits<ReturnInst>::op_end(this) - 689 RI.getNumOperands(), 690 RI.getNumOperands()) { 691 if (RI.getNumOperands()) 692 Op<0>() = RI.Op<0>(); 693 SubclassOptionalData = RI.SubclassOptionalData; 694 } 695 696 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore) 697 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret, 698 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, 699 InsertBefore) { 700 if (retVal) 701 Op<0>() = retVal; 702 } 703 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd) 704 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret, 705 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, 706 InsertAtEnd) { 707 if (retVal) 708 Op<0>() = retVal; 709 } 710 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd) 711 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret, 712 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) { 713 } 714 715 unsigned ReturnInst::getNumSuccessorsV() const { 716 return getNumSuccessors(); 717 } 718 719 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to 720 /// emit the vtable for the class in this translation unit. 721 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) { 722 llvm_unreachable("ReturnInst has no successors!"); 723 } 724 725 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const { 726 llvm_unreachable("ReturnInst has no successors!"); 727 } 728 729 ReturnInst::~ReturnInst() { 730 } 731 732 //===----------------------------------------------------------------------===// 733 // ResumeInst Implementation 734 //===----------------------------------------------------------------------===// 735 736 ResumeInst::ResumeInst(const ResumeInst &RI) 737 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume, 738 OperandTraits<ResumeInst>::op_begin(this), 1) { 739 Op<0>() = RI.Op<0>(); 740 } 741 742 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore) 743 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume, 744 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) { 745 Op<0>() = Exn; 746 } 747 748 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd) 749 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume, 750 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) { 751 Op<0>() = Exn; 752 } 753 754 unsigned ResumeInst::getNumSuccessorsV() const { 755 return getNumSuccessors(); 756 } 757 758 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) { 759 llvm_unreachable("ResumeInst has no successors!"); 760 } 761 762 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const { 763 llvm_unreachable("ResumeInst has no successors!"); 764 } 765 766 //===----------------------------------------------------------------------===// 767 // CleanupEndPadInst Implementation 768 //===----------------------------------------------------------------------===// 769 770 CleanupEndPadInst::CleanupEndPadInst(const CleanupEndPadInst &CEPI) 771 : TerminatorInst(CEPI.getType(), Instruction::CleanupEndPad, 772 OperandTraits<CleanupEndPadInst>::op_end(this) - 773 CEPI.getNumOperands(), 774 CEPI.getNumOperands()) { 775 setInstructionSubclassData(CEPI.getSubclassDataFromInstruction()); 776 setCleanupPad(CEPI.getCleanupPad()); 777 if (BasicBlock *UnwindDest = CEPI.getUnwindDest()) 778 setUnwindDest(UnwindDest); 779 } 780 781 void CleanupEndPadInst::init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB) { 782 setCleanupPad(CleanupPad); 783 if (UnwindBB) { 784 setInstructionSubclassData(getSubclassDataFromInstruction() | 1); 785 setUnwindDest(UnwindBB); 786 } 787 } 788 789 CleanupEndPadInst::CleanupEndPadInst(CleanupPadInst *CleanupPad, 790 BasicBlock *UnwindBB, unsigned Values, 791 Instruction *InsertBefore) 792 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()), 793 Instruction::CleanupEndPad, 794 OperandTraits<CleanupEndPadInst>::op_end(this) - Values, 795 Values, InsertBefore) { 796 init(CleanupPad, UnwindBB); 797 } 798 799 CleanupEndPadInst::CleanupEndPadInst(CleanupPadInst *CleanupPad, 800 BasicBlock *UnwindBB, unsigned Values, 801 BasicBlock *InsertAtEnd) 802 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()), 803 Instruction::CleanupEndPad, 804 OperandTraits<CleanupEndPadInst>::op_end(this) - Values, 805 Values, InsertAtEnd) { 806 init(CleanupPad, UnwindBB); 807 } 808 809 BasicBlock *CleanupEndPadInst::getSuccessorV(unsigned Idx) const { 810 assert(Idx == 0); 811 return getUnwindDest(); 812 } 813 unsigned CleanupEndPadInst::getNumSuccessorsV() const { 814 return getNumSuccessors(); 815 } 816 void CleanupEndPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) { 817 assert(Idx == 0); 818 setUnwindDest(B); 819 } 820 821 //===----------------------------------------------------------------------===// 822 // CleanupReturnInst Implementation 823 //===----------------------------------------------------------------------===// 824 825 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI) 826 : TerminatorInst(CRI.getType(), Instruction::CleanupRet, 827 OperandTraits<CleanupReturnInst>::op_end(this) - 828 CRI.getNumOperands(), 829 CRI.getNumOperands()) { 830 setInstructionSubclassData(CRI.getSubclassDataFromInstruction()); 831 Op<-1>() = CRI.Op<-1>(); 832 if (CRI.hasUnwindDest()) 833 Op<-2>() = CRI.Op<-2>(); 834 } 835 836 void CleanupReturnInst::init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB) { 837 if (UnwindBB) 838 setInstructionSubclassData(getSubclassDataFromInstruction() | 1); 839 840 Op<-1>() = CleanupPad; 841 if (UnwindBB) 842 Op<-2>() = UnwindBB; 843 } 844 845 CleanupReturnInst::CleanupReturnInst(CleanupPadInst *CleanupPad, 846 BasicBlock *UnwindBB, unsigned Values, 847 Instruction *InsertBefore) 848 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()), 849 Instruction::CleanupRet, 850 OperandTraits<CleanupReturnInst>::op_end(this) - Values, 851 Values, InsertBefore) { 852 init(CleanupPad, UnwindBB); 853 } 854 855 CleanupReturnInst::CleanupReturnInst(CleanupPadInst *CleanupPad, 856 BasicBlock *UnwindBB, unsigned Values, 857 BasicBlock *InsertAtEnd) 858 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()), 859 Instruction::CleanupRet, 860 OperandTraits<CleanupReturnInst>::op_end(this) - Values, 861 Values, InsertAtEnd) { 862 init(CleanupPad, UnwindBB); 863 } 864 865 BasicBlock *CleanupReturnInst::getSuccessorV(unsigned Idx) const { 866 assert(Idx == 0); 867 return getUnwindDest(); 868 } 869 unsigned CleanupReturnInst::getNumSuccessorsV() const { 870 return getNumSuccessors(); 871 } 872 void CleanupReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) { 873 assert(Idx == 0); 874 setUnwindDest(B); 875 } 876 877 //===----------------------------------------------------------------------===// 878 // CatchEndPadInst Implementation 879 //===----------------------------------------------------------------------===// 880 881 CatchEndPadInst::CatchEndPadInst(const CatchEndPadInst &CRI) 882 : TerminatorInst(CRI.getType(), Instruction::CatchEndPad, 883 OperandTraits<CatchEndPadInst>::op_end(this) - 884 CRI.getNumOperands(), 885 CRI.getNumOperands()) { 886 setInstructionSubclassData(CRI.getSubclassDataFromInstruction()); 887 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) 888 setUnwindDest(UnwindDest); 889 } 890 891 void CatchEndPadInst::init(BasicBlock *UnwindBB) { 892 if (UnwindBB) { 893 setInstructionSubclassData(getSubclassDataFromInstruction() | 1); 894 setUnwindDest(UnwindBB); 895 } 896 } 897 898 CatchEndPadInst::CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB, 899 unsigned Values, Instruction *InsertBefore) 900 : TerminatorInst(Type::getVoidTy(C), Instruction::CatchEndPad, 901 OperandTraits<CatchEndPadInst>::op_end(this) - Values, 902 Values, InsertBefore) { 903 init(UnwindBB); 904 } 905 906 CatchEndPadInst::CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB, 907 unsigned Values, BasicBlock *InsertAtEnd) 908 : TerminatorInst(Type::getVoidTy(C), Instruction::CatchEndPad, 909 OperandTraits<CatchEndPadInst>::op_end(this) - Values, 910 Values, InsertAtEnd) { 911 init(UnwindBB); 912 } 913 914 BasicBlock *CatchEndPadInst::getSuccessorV(unsigned Idx) const { 915 assert(Idx == 0); 916 return getUnwindDest(); 917 } 918 unsigned CatchEndPadInst::getNumSuccessorsV() const { 919 return getNumSuccessors(); 920 } 921 void CatchEndPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) { 922 assert(Idx == 0); 923 setUnwindDest(B); 924 } 925 926 //===----------------------------------------------------------------------===// 927 // CatchReturnInst Implementation 928 //===----------------------------------------------------------------------===// 929 void CatchReturnInst::init(CatchPadInst *CatchPad, BasicBlock *BB) { 930 Op<0>() = CatchPad; 931 Op<1>() = BB; 932 } 933 934 CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI) 935 : TerminatorInst(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet, 936 OperandTraits<CatchReturnInst>::op_begin(this), 2) { 937 Op<0>() = CRI.Op<0>(); 938 Op<1>() = CRI.Op<1>(); 939 } 940 941 CatchReturnInst::CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB, 942 Instruction *InsertBefore) 943 : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet, 944 OperandTraits<CatchReturnInst>::op_begin(this), 2, 945 InsertBefore) { 946 init(CatchPad, BB); 947 } 948 949 CatchReturnInst::CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB, 950 BasicBlock *InsertAtEnd) 951 : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet, 952 OperandTraits<CatchReturnInst>::op_begin(this), 2, 953 InsertAtEnd) { 954 init(CatchPad, BB); 955 } 956 957 BasicBlock *CatchReturnInst::getSuccessorV(unsigned Idx) const { 958 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!"); 959 return getSuccessor(); 960 } 961 unsigned CatchReturnInst::getNumSuccessorsV() const { 962 return getNumSuccessors(); 963 } 964 void CatchReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) { 965 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!"); 966 setSuccessor(B); 967 } 968 969 //===----------------------------------------------------------------------===// 970 // CatchPadInst Implementation 971 //===----------------------------------------------------------------------===// 972 void CatchPadInst::init(BasicBlock *IfNormal, BasicBlock *IfException, 973 ArrayRef<Value *> Args, const Twine &NameStr) { 974 assert(getNumOperands() == 2 + Args.size() && "NumOperands not set up?"); 975 Op<-2>() = IfNormal; 976 Op<-1>() = IfException; 977 std::copy(Args.begin(), Args.end(), op_begin()); 978 setName(NameStr); 979 } 980 981 CatchPadInst::CatchPadInst(const CatchPadInst &CPI) 982 : TerminatorInst(CPI.getType(), Instruction::CatchPad, 983 OperandTraits<CatchPadInst>::op_end(this) - 984 CPI.getNumOperands(), 985 CPI.getNumOperands()) { 986 std::copy(CPI.op_begin(), CPI.op_end(), op_begin()); 987 } 988 989 CatchPadInst::CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException, 990 ArrayRef<Value *> Args, unsigned Values, 991 const Twine &NameStr, Instruction *InsertBefore) 992 : TerminatorInst(Type::getTokenTy(IfNormal->getContext()), 993 Instruction::CatchPad, 994 OperandTraits<CatchPadInst>::op_end(this) - Values, Values, 995 InsertBefore) { 996 init(IfNormal, IfException, Args, NameStr); 997 } 998 999 CatchPadInst::CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException, 1000 ArrayRef<Value *> Args, unsigned Values, 1001 const Twine &NameStr, BasicBlock *InsertAtEnd) 1002 : TerminatorInst(Type::getTokenTy(IfNormal->getContext()), 1003 Instruction::CatchPad, 1004 OperandTraits<CatchPadInst>::op_end(this) - Values, Values, 1005 InsertAtEnd) { 1006 init(IfNormal, IfException, Args, NameStr); 1007 } 1008 1009 BasicBlock *CatchPadInst::getSuccessorV(unsigned Idx) const { 1010 return getSuccessor(Idx); 1011 } 1012 unsigned CatchPadInst::getNumSuccessorsV() const { 1013 return getNumSuccessors(); 1014 } 1015 void CatchPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) { 1016 return setSuccessor(Idx, B); 1017 } 1018 1019 //===----------------------------------------------------------------------===// 1020 // TerminatePadInst Implementation 1021 //===----------------------------------------------------------------------===// 1022 void TerminatePadInst::init(BasicBlock *BB, ArrayRef<Value *> Args) { 1023 if (BB) 1024 setInstructionSubclassData(getSubclassDataFromInstruction() | 1); 1025 if (BB) 1026 Op<-1>() = BB; 1027 std::copy(Args.begin(), Args.end(), op_begin()); 1028 } 1029 1030 TerminatePadInst::TerminatePadInst(const TerminatePadInst &TPI) 1031 : TerminatorInst(TPI.getType(), Instruction::TerminatePad, 1032 OperandTraits<TerminatePadInst>::op_end(this) - 1033 TPI.getNumOperands(), 1034 TPI.getNumOperands()) { 1035 setInstructionSubclassData(TPI.getSubclassDataFromInstruction()); 1036 std::copy(TPI.op_begin(), TPI.op_end(), op_begin()); 1037 } 1038 1039 TerminatePadInst::TerminatePadInst(LLVMContext &C, BasicBlock *BB, 1040 ArrayRef<Value *> Args, unsigned Values, 1041 Instruction *InsertBefore) 1042 : TerminatorInst(Type::getVoidTy(C), Instruction::TerminatePad, 1043 OperandTraits<TerminatePadInst>::op_end(this) - Values, 1044 Values, InsertBefore) { 1045 init(BB, Args); 1046 } 1047 1048 TerminatePadInst::TerminatePadInst(LLVMContext &C, BasicBlock *BB, 1049 ArrayRef<Value *> Args, unsigned Values, 1050 BasicBlock *InsertAtEnd) 1051 : TerminatorInst(Type::getVoidTy(C), Instruction::TerminatePad, 1052 OperandTraits<TerminatePadInst>::op_end(this) - Values, 1053 Values, InsertAtEnd) { 1054 init(BB, Args); 1055 } 1056 1057 BasicBlock *TerminatePadInst::getSuccessorV(unsigned Idx) const { 1058 assert(Idx == 0); 1059 return getUnwindDest(); 1060 } 1061 unsigned TerminatePadInst::getNumSuccessorsV() const { 1062 return getNumSuccessors(); 1063 } 1064 void TerminatePadInst::setSuccessorV(unsigned Idx, BasicBlock *B) { 1065 assert(Idx == 0); 1066 return setUnwindDest(B); 1067 } 1068 1069 //===----------------------------------------------------------------------===// 1070 // CleanupPadInst Implementation 1071 //===----------------------------------------------------------------------===// 1072 void CleanupPadInst::init(ArrayRef<Value *> Args, const Twine &NameStr) { 1073 assert(getNumOperands() == Args.size() && "NumOperands not set up?"); 1074 std::copy(Args.begin(), Args.end(), op_begin()); 1075 setName(NameStr); 1076 } 1077 1078 CleanupPadInst::CleanupPadInst(const CleanupPadInst &CPI) 1079 : Instruction(CPI.getType(), Instruction::CleanupPad, 1080 OperandTraits<CleanupPadInst>::op_end(this) - 1081 CPI.getNumOperands(), 1082 CPI.getNumOperands()) { 1083 std::copy(CPI.op_begin(), CPI.op_end(), op_begin()); 1084 } 1085 1086 CleanupPadInst::CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args, 1087 const Twine &NameStr, Instruction *InsertBefore) 1088 : Instruction(Type::getTokenTy(C), Instruction::CleanupPad, 1089 OperandTraits<CleanupPadInst>::op_end(this) - Args.size(), 1090 Args.size(), InsertBefore) { 1091 init(Args, NameStr); 1092 } 1093 1094 CleanupPadInst::CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args, 1095 const Twine &NameStr, BasicBlock *InsertAtEnd) 1096 : Instruction(Type::getTokenTy(C), Instruction::CleanupPad, 1097 OperandTraits<CleanupPadInst>::op_end(this) - Args.size(), 1098 Args.size(), InsertAtEnd) { 1099 init(Args, NameStr); 1100 } 1101 1102 //===----------------------------------------------------------------------===// 1103 // UnreachableInst Implementation 1104 //===----------------------------------------------------------------------===// 1105 1106 UnreachableInst::UnreachableInst(LLVMContext &Context, 1107 Instruction *InsertBefore) 1108 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable, 1109 nullptr, 0, InsertBefore) { 1110 } 1111 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd) 1112 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable, 1113 nullptr, 0, InsertAtEnd) { 1114 } 1115 1116 unsigned UnreachableInst::getNumSuccessorsV() const { 1117 return getNumSuccessors(); 1118 } 1119 1120 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) { 1121 llvm_unreachable("UnreachableInst has no successors!"); 1122 } 1123 1124 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const { 1125 llvm_unreachable("UnreachableInst has no successors!"); 1126 } 1127 1128 //===----------------------------------------------------------------------===// 1129 // BranchInst Implementation 1130 //===----------------------------------------------------------------------===// 1131 1132 void BranchInst::AssertOK() { 1133 if (isConditional()) 1134 assert(getCondition()->getType()->isIntegerTy(1) && 1135 "May only branch on boolean predicates!"); 1136 } 1137 1138 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore) 1139 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1140 OperandTraits<BranchInst>::op_end(this) - 1, 1141 1, InsertBefore) { 1142 assert(IfTrue && "Branch destination may not be null!"); 1143 Op<-1>() = IfTrue; 1144 } 1145 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, 1146 Instruction *InsertBefore) 1147 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1148 OperandTraits<BranchInst>::op_end(this) - 3, 1149 3, InsertBefore) { 1150 Op<-1>() = IfTrue; 1151 Op<-2>() = IfFalse; 1152 Op<-3>() = Cond; 1153 #ifndef NDEBUG 1154 AssertOK(); 1155 #endif 1156 } 1157 1158 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) 1159 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1160 OperandTraits<BranchInst>::op_end(this) - 1, 1161 1, InsertAtEnd) { 1162 assert(IfTrue && "Branch destination may not be null!"); 1163 Op<-1>() = IfTrue; 1164 } 1165 1166 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, 1167 BasicBlock *InsertAtEnd) 1168 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1169 OperandTraits<BranchInst>::op_end(this) - 3, 1170 3, InsertAtEnd) { 1171 Op<-1>() = IfTrue; 1172 Op<-2>() = IfFalse; 1173 Op<-3>() = Cond; 1174 #ifndef NDEBUG 1175 AssertOK(); 1176 #endif 1177 } 1178 1179 1180 BranchInst::BranchInst(const BranchInst &BI) : 1181 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br, 1182 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(), 1183 BI.getNumOperands()) { 1184 Op<-1>() = BI.Op<-1>(); 1185 if (BI.getNumOperands() != 1) { 1186 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!"); 1187 Op<-3>() = BI.Op<-3>(); 1188 Op<-2>() = BI.Op<-2>(); 1189 } 1190 SubclassOptionalData = BI.SubclassOptionalData; 1191 } 1192 1193 void BranchInst::swapSuccessors() { 1194 assert(isConditional() && 1195 "Cannot swap successors of an unconditional branch"); 1196 Op<-1>().swap(Op<-2>()); 1197 1198 // Update profile metadata if present and it matches our structural 1199 // expectations. 1200 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof); 1201 if (!ProfileData || ProfileData->getNumOperands() != 3) 1202 return; 1203 1204 // The first operand is the name. Fetch them backwards and build a new one. 1205 Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2), 1206 ProfileData->getOperand(1)}; 1207 setMetadata(LLVMContext::MD_prof, 1208 MDNode::get(ProfileData->getContext(), Ops)); 1209 } 1210 1211 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const { 1212 return getSuccessor(idx); 1213 } 1214 unsigned BranchInst::getNumSuccessorsV() const { 1215 return getNumSuccessors(); 1216 } 1217 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) { 1218 setSuccessor(idx, B); 1219 } 1220 1221 1222 //===----------------------------------------------------------------------===// 1223 // AllocaInst Implementation 1224 //===----------------------------------------------------------------------===// 1225 1226 static Value *getAISize(LLVMContext &Context, Value *Amt) { 1227 if (!Amt) 1228 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1); 1229 else { 1230 assert(!isa<BasicBlock>(Amt) && 1231 "Passed basic block into allocation size parameter! Use other ctor"); 1232 assert(Amt->getType()->isIntegerTy() && 1233 "Allocation array size is not an integer!"); 1234 } 1235 return Amt; 1236 } 1237 1238 AllocaInst::AllocaInst(Type *Ty, const Twine &Name, Instruction *InsertBefore) 1239 : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertBefore) {} 1240 1241 AllocaInst::AllocaInst(Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd) 1242 : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertAtEnd) {} 1243 1244 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name, 1245 Instruction *InsertBefore) 1246 : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertBefore) {} 1247 1248 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name, 1249 BasicBlock *InsertAtEnd) 1250 : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertAtEnd) {} 1251 1252 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align, 1253 const Twine &Name, Instruction *InsertBefore) 1254 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca, 1255 getAISize(Ty->getContext(), ArraySize), InsertBefore), 1256 AllocatedType(Ty) { 1257 setAlignment(Align); 1258 assert(!Ty->isVoidTy() && "Cannot allocate void!"); 1259 setName(Name); 1260 } 1261 1262 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align, 1263 const Twine &Name, BasicBlock *InsertAtEnd) 1264 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca, 1265 getAISize(Ty->getContext(), ArraySize), InsertAtEnd), 1266 AllocatedType(Ty) { 1267 setAlignment(Align); 1268 assert(!Ty->isVoidTy() && "Cannot allocate void!"); 1269 setName(Name); 1270 } 1271 1272 // Out of line virtual method, so the vtable, etc has a home. 1273 AllocaInst::~AllocaInst() { 1274 } 1275 1276 void AllocaInst::setAlignment(unsigned Align) { 1277 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 1278 assert(Align <= MaximumAlignment && 1279 "Alignment is greater than MaximumAlignment!"); 1280 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) | 1281 (Log2_32(Align) + 1)); 1282 assert(getAlignment() == Align && "Alignment representation error!"); 1283 } 1284 1285 bool AllocaInst::isArrayAllocation() const { 1286 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0))) 1287 return !CI->isOne(); 1288 return true; 1289 } 1290 1291 /// isStaticAlloca - Return true if this alloca is in the entry block of the 1292 /// function and is a constant size. If so, the code generator will fold it 1293 /// into the prolog/epilog code, so it is basically free. 1294 bool AllocaInst::isStaticAlloca() const { 1295 // Must be constant size. 1296 if (!isa<ConstantInt>(getArraySize())) return false; 1297 1298 // Must be in the entry block. 1299 const BasicBlock *Parent = getParent(); 1300 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca(); 1301 } 1302 1303 //===----------------------------------------------------------------------===// 1304 // LoadInst Implementation 1305 //===----------------------------------------------------------------------===// 1306 1307 void LoadInst::AssertOK() { 1308 assert(getOperand(0)->getType()->isPointerTy() && 1309 "Ptr must have pointer type."); 1310 assert(!(isAtomic() && getAlignment() == 0) && 1311 "Alignment required for atomic load"); 1312 } 1313 1314 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef) 1315 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertBef) {} 1316 1317 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE) 1318 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertAE) {} 1319 1320 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1321 Instruction *InsertBef) 1322 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertBef) {} 1323 1324 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 1325 BasicBlock *InsertAE) 1326 : LoadInst(Ptr, Name, isVolatile, /*Align=*/0, InsertAE) {} 1327 1328 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1329 unsigned Align, Instruction *InsertBef) 1330 : LoadInst(Ty, Ptr, Name, isVolatile, Align, NotAtomic, CrossThread, 1331 InsertBef) {} 1332 1333 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 1334 unsigned Align, BasicBlock *InsertAE) 1335 : LoadInst(Ptr, Name, isVolatile, Align, NotAtomic, CrossThread, InsertAE) { 1336 } 1337 1338 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1339 unsigned Align, AtomicOrdering Order, 1340 SynchronizationScope SynchScope, Instruction *InsertBef) 1341 : UnaryInstruction(Ty, Load, Ptr, InsertBef) { 1342 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType()); 1343 setVolatile(isVolatile); 1344 setAlignment(Align); 1345 setAtomic(Order, SynchScope); 1346 AssertOK(); 1347 setName(Name); 1348 } 1349 1350 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 1351 unsigned Align, AtomicOrdering Order, 1352 SynchronizationScope SynchScope, 1353 BasicBlock *InsertAE) 1354 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 1355 Load, Ptr, InsertAE) { 1356 setVolatile(isVolatile); 1357 setAlignment(Align); 1358 setAtomic(Order, SynchScope); 1359 AssertOK(); 1360 setName(Name); 1361 } 1362 1363 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef) 1364 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 1365 Load, Ptr, InsertBef) { 1366 setVolatile(false); 1367 setAlignment(0); 1368 setAtomic(NotAtomic); 1369 AssertOK(); 1370 if (Name && Name[0]) setName(Name); 1371 } 1372 1373 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE) 1374 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 1375 Load, Ptr, InsertAE) { 1376 setVolatile(false); 1377 setAlignment(0); 1378 setAtomic(NotAtomic); 1379 AssertOK(); 1380 if (Name && Name[0]) setName(Name); 1381 } 1382 1383 LoadInst::LoadInst(Type *Ty, Value *Ptr, const char *Name, bool isVolatile, 1384 Instruction *InsertBef) 1385 : UnaryInstruction(Ty, Load, Ptr, InsertBef) { 1386 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType()); 1387 setVolatile(isVolatile); 1388 setAlignment(0); 1389 setAtomic(NotAtomic); 1390 AssertOK(); 1391 if (Name && Name[0]) setName(Name); 1392 } 1393 1394 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile, 1395 BasicBlock *InsertAE) 1396 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 1397 Load, Ptr, InsertAE) { 1398 setVolatile(isVolatile); 1399 setAlignment(0); 1400 setAtomic(NotAtomic); 1401 AssertOK(); 1402 if (Name && Name[0]) setName(Name); 1403 } 1404 1405 void LoadInst::setAlignment(unsigned Align) { 1406 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 1407 assert(Align <= MaximumAlignment && 1408 "Alignment is greater than MaximumAlignment!"); 1409 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) | 1410 ((Log2_32(Align)+1)<<1)); 1411 assert(getAlignment() == Align && "Alignment representation error!"); 1412 } 1413 1414 //===----------------------------------------------------------------------===// 1415 // StoreInst Implementation 1416 //===----------------------------------------------------------------------===// 1417 1418 void StoreInst::AssertOK() { 1419 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!"); 1420 assert(getOperand(1)->getType()->isPointerTy() && 1421 "Ptr must have pointer type!"); 1422 assert(getOperand(0)->getType() == 1423 cast<PointerType>(getOperand(1)->getType())->getElementType() 1424 && "Ptr must be a pointer to Val type!"); 1425 assert(!(isAtomic() && getAlignment() == 0) && 1426 "Alignment required for atomic store"); 1427 } 1428 1429 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore) 1430 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {} 1431 1432 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd) 1433 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {} 1434 1435 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1436 Instruction *InsertBefore) 1437 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertBefore) {} 1438 1439 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1440 BasicBlock *InsertAtEnd) 1441 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertAtEnd) {} 1442 1443 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align, 1444 Instruction *InsertBefore) 1445 : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread, 1446 InsertBefore) {} 1447 1448 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align, 1449 BasicBlock *InsertAtEnd) 1450 : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread, 1451 InsertAtEnd) {} 1452 1453 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1454 unsigned Align, AtomicOrdering Order, 1455 SynchronizationScope SynchScope, 1456 Instruction *InsertBefore) 1457 : Instruction(Type::getVoidTy(val->getContext()), Store, 1458 OperandTraits<StoreInst>::op_begin(this), 1459 OperandTraits<StoreInst>::operands(this), 1460 InsertBefore) { 1461 Op<0>() = val; 1462 Op<1>() = addr; 1463 setVolatile(isVolatile); 1464 setAlignment(Align); 1465 setAtomic(Order, SynchScope); 1466 AssertOK(); 1467 } 1468 1469 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1470 unsigned Align, AtomicOrdering Order, 1471 SynchronizationScope SynchScope, 1472 BasicBlock *InsertAtEnd) 1473 : Instruction(Type::getVoidTy(val->getContext()), Store, 1474 OperandTraits<StoreInst>::op_begin(this), 1475 OperandTraits<StoreInst>::operands(this), 1476 InsertAtEnd) { 1477 Op<0>() = val; 1478 Op<1>() = addr; 1479 setVolatile(isVolatile); 1480 setAlignment(Align); 1481 setAtomic(Order, SynchScope); 1482 AssertOK(); 1483 } 1484 1485 void StoreInst::setAlignment(unsigned Align) { 1486 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 1487 assert(Align <= MaximumAlignment && 1488 "Alignment is greater than MaximumAlignment!"); 1489 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) | 1490 ((Log2_32(Align)+1) << 1)); 1491 assert(getAlignment() == Align && "Alignment representation error!"); 1492 } 1493 1494 //===----------------------------------------------------------------------===// 1495 // AtomicCmpXchgInst Implementation 1496 //===----------------------------------------------------------------------===// 1497 1498 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal, 1499 AtomicOrdering SuccessOrdering, 1500 AtomicOrdering FailureOrdering, 1501 SynchronizationScope SynchScope) { 1502 Op<0>() = Ptr; 1503 Op<1>() = Cmp; 1504 Op<2>() = NewVal; 1505 setSuccessOrdering(SuccessOrdering); 1506 setFailureOrdering(FailureOrdering); 1507 setSynchScope(SynchScope); 1508 1509 assert(getOperand(0) && getOperand(1) && getOperand(2) && 1510 "All operands must be non-null!"); 1511 assert(getOperand(0)->getType()->isPointerTy() && 1512 "Ptr must have pointer type!"); 1513 assert(getOperand(1)->getType() == 1514 cast<PointerType>(getOperand(0)->getType())->getElementType() 1515 && "Ptr must be a pointer to Cmp type!"); 1516 assert(getOperand(2)->getType() == 1517 cast<PointerType>(getOperand(0)->getType())->getElementType() 1518 && "Ptr must be a pointer to NewVal type!"); 1519 assert(SuccessOrdering != NotAtomic && 1520 "AtomicCmpXchg instructions must be atomic!"); 1521 assert(FailureOrdering != NotAtomic && 1522 "AtomicCmpXchg instructions must be atomic!"); 1523 assert(SuccessOrdering >= FailureOrdering && 1524 "AtomicCmpXchg success ordering must be at least as strong as fail"); 1525 assert(FailureOrdering != Release && FailureOrdering != AcquireRelease && 1526 "AtomicCmpXchg failure ordering cannot include release semantics"); 1527 } 1528 1529 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, 1530 AtomicOrdering SuccessOrdering, 1531 AtomicOrdering FailureOrdering, 1532 SynchronizationScope SynchScope, 1533 Instruction *InsertBefore) 1534 : Instruction( 1535 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()), 1536 nullptr), 1537 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), 1538 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) { 1539 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope); 1540 } 1541 1542 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, 1543 AtomicOrdering SuccessOrdering, 1544 AtomicOrdering FailureOrdering, 1545 SynchronizationScope SynchScope, 1546 BasicBlock *InsertAtEnd) 1547 : Instruction( 1548 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()), 1549 nullptr), 1550 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), 1551 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) { 1552 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope); 1553 } 1554 1555 //===----------------------------------------------------------------------===// 1556 // AtomicRMWInst Implementation 1557 //===----------------------------------------------------------------------===// 1558 1559 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val, 1560 AtomicOrdering Ordering, 1561 SynchronizationScope SynchScope) { 1562 Op<0>() = Ptr; 1563 Op<1>() = Val; 1564 setOperation(Operation); 1565 setOrdering(Ordering); 1566 setSynchScope(SynchScope); 1567 1568 assert(getOperand(0) && getOperand(1) && 1569 "All operands must be non-null!"); 1570 assert(getOperand(0)->getType()->isPointerTy() && 1571 "Ptr must have pointer type!"); 1572 assert(getOperand(1)->getType() == 1573 cast<PointerType>(getOperand(0)->getType())->getElementType() 1574 && "Ptr must be a pointer to Val type!"); 1575 assert(Ordering != NotAtomic && 1576 "AtomicRMW instructions must be atomic!"); 1577 } 1578 1579 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, 1580 AtomicOrdering Ordering, 1581 SynchronizationScope SynchScope, 1582 Instruction *InsertBefore) 1583 : Instruction(Val->getType(), AtomicRMW, 1584 OperandTraits<AtomicRMWInst>::op_begin(this), 1585 OperandTraits<AtomicRMWInst>::operands(this), 1586 InsertBefore) { 1587 Init(Operation, Ptr, Val, Ordering, SynchScope); 1588 } 1589 1590 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, 1591 AtomicOrdering Ordering, 1592 SynchronizationScope SynchScope, 1593 BasicBlock *InsertAtEnd) 1594 : Instruction(Val->getType(), AtomicRMW, 1595 OperandTraits<AtomicRMWInst>::op_begin(this), 1596 OperandTraits<AtomicRMWInst>::operands(this), 1597 InsertAtEnd) { 1598 Init(Operation, Ptr, Val, Ordering, SynchScope); 1599 } 1600 1601 //===----------------------------------------------------------------------===// 1602 // FenceInst Implementation 1603 //===----------------------------------------------------------------------===// 1604 1605 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 1606 SynchronizationScope SynchScope, 1607 Instruction *InsertBefore) 1608 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) { 1609 setOrdering(Ordering); 1610 setSynchScope(SynchScope); 1611 } 1612 1613 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 1614 SynchronizationScope SynchScope, 1615 BasicBlock *InsertAtEnd) 1616 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) { 1617 setOrdering(Ordering); 1618 setSynchScope(SynchScope); 1619 } 1620 1621 //===----------------------------------------------------------------------===// 1622 // GetElementPtrInst Implementation 1623 //===----------------------------------------------------------------------===// 1624 1625 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList, 1626 const Twine &Name) { 1627 assert(getNumOperands() == 1 + IdxList.size() && 1628 "NumOperands not initialized?"); 1629 Op<0>() = Ptr; 1630 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1); 1631 setName(Name); 1632 } 1633 1634 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI) 1635 : Instruction(GEPI.getType(), GetElementPtr, 1636 OperandTraits<GetElementPtrInst>::op_end(this) - 1637 GEPI.getNumOperands(), 1638 GEPI.getNumOperands()), 1639 SourceElementType(GEPI.SourceElementType), 1640 ResultElementType(GEPI.ResultElementType) { 1641 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin()); 1642 SubclassOptionalData = GEPI.SubclassOptionalData; 1643 } 1644 1645 /// getIndexedType - Returns the type of the element that would be accessed with 1646 /// a gep instruction with the specified parameters. 1647 /// 1648 /// The Idxs pointer should point to a continuous piece of memory containing the 1649 /// indices, either as Value* or uint64_t. 1650 /// 1651 /// A null type is returned if the indices are invalid for the specified 1652 /// pointer type. 1653 /// 1654 template <typename IndexTy> 1655 static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) { 1656 // Handle the special case of the empty set index set, which is always valid. 1657 if (IdxList.empty()) 1658 return Agg; 1659 1660 // If there is at least one index, the top level type must be sized, otherwise 1661 // it cannot be 'stepped over'. 1662 if (!Agg->isSized()) 1663 return nullptr; 1664 1665 unsigned CurIdx = 1; 1666 for (; CurIdx != IdxList.size(); ++CurIdx) { 1667 CompositeType *CT = dyn_cast<CompositeType>(Agg); 1668 if (!CT || CT->isPointerTy()) return nullptr; 1669 IndexTy Index = IdxList[CurIdx]; 1670 if (!CT->indexValid(Index)) return nullptr; 1671 Agg = CT->getTypeAtIndex(Index); 1672 } 1673 return CurIdx == IdxList.size() ? Agg : nullptr; 1674 } 1675 1676 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) { 1677 return getIndexedTypeInternal(Ty, IdxList); 1678 } 1679 1680 Type *GetElementPtrInst::getIndexedType(Type *Ty, 1681 ArrayRef<Constant *> IdxList) { 1682 return getIndexedTypeInternal(Ty, IdxList); 1683 } 1684 1685 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) { 1686 return getIndexedTypeInternal(Ty, IdxList); 1687 } 1688 1689 /// hasAllZeroIndices - Return true if all of the indices of this GEP are 1690 /// zeros. If so, the result pointer and the first operand have the same 1691 /// value, just potentially different types. 1692 bool GetElementPtrInst::hasAllZeroIndices() const { 1693 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1694 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) { 1695 if (!CI->isZero()) return false; 1696 } else { 1697 return false; 1698 } 1699 } 1700 return true; 1701 } 1702 1703 /// hasAllConstantIndices - Return true if all of the indices of this GEP are 1704 /// constant integers. If so, the result pointer and the first operand have 1705 /// a constant offset between them. 1706 bool GetElementPtrInst::hasAllConstantIndices() const { 1707 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1708 if (!isa<ConstantInt>(getOperand(i))) 1709 return false; 1710 } 1711 return true; 1712 } 1713 1714 void GetElementPtrInst::setIsInBounds(bool B) { 1715 cast<GEPOperator>(this)->setIsInBounds(B); 1716 } 1717 1718 bool GetElementPtrInst::isInBounds() const { 1719 return cast<GEPOperator>(this)->isInBounds(); 1720 } 1721 1722 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL, 1723 APInt &Offset) const { 1724 // Delegate to the generic GEPOperator implementation. 1725 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset); 1726 } 1727 1728 //===----------------------------------------------------------------------===// 1729 // ExtractElementInst Implementation 1730 //===----------------------------------------------------------------------===// 1731 1732 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1733 const Twine &Name, 1734 Instruction *InsertBef) 1735 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1736 ExtractElement, 1737 OperandTraits<ExtractElementInst>::op_begin(this), 1738 2, InsertBef) { 1739 assert(isValidOperands(Val, Index) && 1740 "Invalid extractelement instruction operands!"); 1741 Op<0>() = Val; 1742 Op<1>() = Index; 1743 setName(Name); 1744 } 1745 1746 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1747 const Twine &Name, 1748 BasicBlock *InsertAE) 1749 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1750 ExtractElement, 1751 OperandTraits<ExtractElementInst>::op_begin(this), 1752 2, InsertAE) { 1753 assert(isValidOperands(Val, Index) && 1754 "Invalid extractelement instruction operands!"); 1755 1756 Op<0>() = Val; 1757 Op<1>() = Index; 1758 setName(Name); 1759 } 1760 1761 1762 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) { 1763 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy()) 1764 return false; 1765 return true; 1766 } 1767 1768 1769 //===----------------------------------------------------------------------===// 1770 // InsertElementInst Implementation 1771 //===----------------------------------------------------------------------===// 1772 1773 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1774 const Twine &Name, 1775 Instruction *InsertBef) 1776 : Instruction(Vec->getType(), InsertElement, 1777 OperandTraits<InsertElementInst>::op_begin(this), 1778 3, InsertBef) { 1779 assert(isValidOperands(Vec, Elt, Index) && 1780 "Invalid insertelement instruction operands!"); 1781 Op<0>() = Vec; 1782 Op<1>() = Elt; 1783 Op<2>() = Index; 1784 setName(Name); 1785 } 1786 1787 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1788 const Twine &Name, 1789 BasicBlock *InsertAE) 1790 : Instruction(Vec->getType(), InsertElement, 1791 OperandTraits<InsertElementInst>::op_begin(this), 1792 3, InsertAE) { 1793 assert(isValidOperands(Vec, Elt, Index) && 1794 "Invalid insertelement instruction operands!"); 1795 1796 Op<0>() = Vec; 1797 Op<1>() = Elt; 1798 Op<2>() = Index; 1799 setName(Name); 1800 } 1801 1802 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 1803 const Value *Index) { 1804 if (!Vec->getType()->isVectorTy()) 1805 return false; // First operand of insertelement must be vector type. 1806 1807 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType()) 1808 return false;// Second operand of insertelement must be vector element type. 1809 1810 if (!Index->getType()->isIntegerTy()) 1811 return false; // Third operand of insertelement must be i32. 1812 return true; 1813 } 1814 1815 1816 //===----------------------------------------------------------------------===// 1817 // ShuffleVectorInst Implementation 1818 //===----------------------------------------------------------------------===// 1819 1820 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1821 const Twine &Name, 1822 Instruction *InsertBefore) 1823 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1824 cast<VectorType>(Mask->getType())->getNumElements()), 1825 ShuffleVector, 1826 OperandTraits<ShuffleVectorInst>::op_begin(this), 1827 OperandTraits<ShuffleVectorInst>::operands(this), 1828 InsertBefore) { 1829 assert(isValidOperands(V1, V2, Mask) && 1830 "Invalid shuffle vector instruction operands!"); 1831 Op<0>() = V1; 1832 Op<1>() = V2; 1833 Op<2>() = Mask; 1834 setName(Name); 1835 } 1836 1837 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1838 const Twine &Name, 1839 BasicBlock *InsertAtEnd) 1840 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1841 cast<VectorType>(Mask->getType())->getNumElements()), 1842 ShuffleVector, 1843 OperandTraits<ShuffleVectorInst>::op_begin(this), 1844 OperandTraits<ShuffleVectorInst>::operands(this), 1845 InsertAtEnd) { 1846 assert(isValidOperands(V1, V2, Mask) && 1847 "Invalid shuffle vector instruction operands!"); 1848 1849 Op<0>() = V1; 1850 Op<1>() = V2; 1851 Op<2>() = Mask; 1852 setName(Name); 1853 } 1854 1855 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 1856 const Value *Mask) { 1857 // V1 and V2 must be vectors of the same type. 1858 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType()) 1859 return false; 1860 1861 // Mask must be vector of i32. 1862 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType()); 1863 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32)) 1864 return false; 1865 1866 // Check to see if Mask is valid. 1867 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask)) 1868 return true; 1869 1870 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) { 1871 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements(); 1872 for (Value *Op : MV->operands()) { 1873 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { 1874 if (CI->uge(V1Size*2)) 1875 return false; 1876 } else if (!isa<UndefValue>(Op)) { 1877 return false; 1878 } 1879 } 1880 return true; 1881 } 1882 1883 if (const ConstantDataSequential *CDS = 1884 dyn_cast<ConstantDataSequential>(Mask)) { 1885 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements(); 1886 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i) 1887 if (CDS->getElementAsInteger(i) >= V1Size*2) 1888 return false; 1889 return true; 1890 } 1891 1892 // The bitcode reader can create a place holder for a forward reference 1893 // used as the shuffle mask. When this occurs, the shuffle mask will 1894 // fall into this case and fail. To avoid this error, do this bit of 1895 // ugliness to allow such a mask pass. 1896 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask)) 1897 if (CE->getOpcode() == Instruction::UserOp1) 1898 return true; 1899 1900 return false; 1901 } 1902 1903 /// getMaskValue - Return the index from the shuffle mask for the specified 1904 /// output result. This is either -1 if the element is undef or a number less 1905 /// than 2*numelements. 1906 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) { 1907 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range"); 1908 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask)) 1909 return CDS->getElementAsInteger(i); 1910 Constant *C = Mask->getAggregateElement(i); 1911 if (isa<UndefValue>(C)) 1912 return -1; 1913 return cast<ConstantInt>(C)->getZExtValue(); 1914 } 1915 1916 /// getShuffleMask - Return the full mask for this instruction, where each 1917 /// element is the element number and undef's are returned as -1. 1918 void ShuffleVectorInst::getShuffleMask(Constant *Mask, 1919 SmallVectorImpl<int> &Result) { 1920 unsigned NumElts = Mask->getType()->getVectorNumElements(); 1921 1922 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) { 1923 for (unsigned i = 0; i != NumElts; ++i) 1924 Result.push_back(CDS->getElementAsInteger(i)); 1925 return; 1926 } 1927 for (unsigned i = 0; i != NumElts; ++i) { 1928 Constant *C = Mask->getAggregateElement(i); 1929 Result.push_back(isa<UndefValue>(C) ? -1 : 1930 cast<ConstantInt>(C)->getZExtValue()); 1931 } 1932 } 1933 1934 1935 //===----------------------------------------------------------------------===// 1936 // InsertValueInst Class 1937 //===----------------------------------------------------------------------===// 1938 1939 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, 1940 const Twine &Name) { 1941 assert(getNumOperands() == 2 && "NumOperands not initialized?"); 1942 1943 // There's no fundamental reason why we require at least one index 1944 // (other than weirdness with &*IdxBegin being invalid; see 1945 // getelementptr's init routine for example). But there's no 1946 // present need to support it. 1947 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index"); 1948 1949 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) == 1950 Val->getType() && "Inserted value must match indexed type!"); 1951 Op<0>() = Agg; 1952 Op<1>() = Val; 1953 1954 Indices.append(Idxs.begin(), Idxs.end()); 1955 setName(Name); 1956 } 1957 1958 InsertValueInst::InsertValueInst(const InsertValueInst &IVI) 1959 : Instruction(IVI.getType(), InsertValue, 1960 OperandTraits<InsertValueInst>::op_begin(this), 2), 1961 Indices(IVI.Indices) { 1962 Op<0>() = IVI.getOperand(0); 1963 Op<1>() = IVI.getOperand(1); 1964 SubclassOptionalData = IVI.SubclassOptionalData; 1965 } 1966 1967 //===----------------------------------------------------------------------===// 1968 // ExtractValueInst Class 1969 //===----------------------------------------------------------------------===// 1970 1971 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) { 1972 assert(getNumOperands() == 1 && "NumOperands not initialized?"); 1973 1974 // There's no fundamental reason why we require at least one index. 1975 // But there's no present need to support it. 1976 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index"); 1977 1978 Indices.append(Idxs.begin(), Idxs.end()); 1979 setName(Name); 1980 } 1981 1982 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI) 1983 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)), 1984 Indices(EVI.Indices) { 1985 SubclassOptionalData = EVI.SubclassOptionalData; 1986 } 1987 1988 // getIndexedType - Returns the type of the element that would be extracted 1989 // with an extractvalue instruction with the specified parameters. 1990 // 1991 // A null type is returned if the indices are invalid for the specified 1992 // pointer type. 1993 // 1994 Type *ExtractValueInst::getIndexedType(Type *Agg, 1995 ArrayRef<unsigned> Idxs) { 1996 for (unsigned Index : Idxs) { 1997 // We can't use CompositeType::indexValid(Index) here. 1998 // indexValid() always returns true for arrays because getelementptr allows 1999 // out-of-bounds indices. Since we don't allow those for extractvalue and 2000 // insertvalue we need to check array indexing manually. 2001 // Since the only other types we can index into are struct types it's just 2002 // as easy to check those manually as well. 2003 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) { 2004 if (Index >= AT->getNumElements()) 2005 return nullptr; 2006 } else if (StructType *ST = dyn_cast<StructType>(Agg)) { 2007 if (Index >= ST->getNumElements()) 2008 return nullptr; 2009 } else { 2010 // Not a valid type to index into. 2011 return nullptr; 2012 } 2013 2014 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index); 2015 } 2016 return const_cast<Type*>(Agg); 2017 } 2018 2019 //===----------------------------------------------------------------------===// 2020 // BinaryOperator Class 2021 //===----------------------------------------------------------------------===// 2022 2023 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 2024 Type *Ty, const Twine &Name, 2025 Instruction *InsertBefore) 2026 : Instruction(Ty, iType, 2027 OperandTraits<BinaryOperator>::op_begin(this), 2028 OperandTraits<BinaryOperator>::operands(this), 2029 InsertBefore) { 2030 Op<0>() = S1; 2031 Op<1>() = S2; 2032 init(iType); 2033 setName(Name); 2034 } 2035 2036 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 2037 Type *Ty, const Twine &Name, 2038 BasicBlock *InsertAtEnd) 2039 : Instruction(Ty, iType, 2040 OperandTraits<BinaryOperator>::op_begin(this), 2041 OperandTraits<BinaryOperator>::operands(this), 2042 InsertAtEnd) { 2043 Op<0>() = S1; 2044 Op<1>() = S2; 2045 init(iType); 2046 setName(Name); 2047 } 2048 2049 2050 void BinaryOperator::init(BinaryOps iType) { 2051 Value *LHS = getOperand(0), *RHS = getOperand(1); 2052 (void)LHS; (void)RHS; // Silence warnings. 2053 assert(LHS->getType() == RHS->getType() && 2054 "Binary operator operand types must match!"); 2055 #ifndef NDEBUG 2056 switch (iType) { 2057 case Add: case Sub: 2058 case Mul: 2059 assert(getType() == LHS->getType() && 2060 "Arithmetic operation should return same type as operands!"); 2061 assert(getType()->isIntOrIntVectorTy() && 2062 "Tried to create an integer operation on a non-integer type!"); 2063 break; 2064 case FAdd: case FSub: 2065 case FMul: 2066 assert(getType() == LHS->getType() && 2067 "Arithmetic operation should return same type as operands!"); 2068 assert(getType()->isFPOrFPVectorTy() && 2069 "Tried to create a floating-point operation on a " 2070 "non-floating-point type!"); 2071 break; 2072 case UDiv: 2073 case SDiv: 2074 assert(getType() == LHS->getType() && 2075 "Arithmetic operation should return same type as operands!"); 2076 assert((getType()->isIntegerTy() || (getType()->isVectorTy() && 2077 cast<VectorType>(getType())->getElementType()->isIntegerTy())) && 2078 "Incorrect operand type (not integer) for S/UDIV"); 2079 break; 2080 case FDiv: 2081 assert(getType() == LHS->getType() && 2082 "Arithmetic operation should return same type as operands!"); 2083 assert(getType()->isFPOrFPVectorTy() && 2084 "Incorrect operand type (not floating point) for FDIV"); 2085 break; 2086 case URem: 2087 case SRem: 2088 assert(getType() == LHS->getType() && 2089 "Arithmetic operation should return same type as operands!"); 2090 assert((getType()->isIntegerTy() || (getType()->isVectorTy() && 2091 cast<VectorType>(getType())->getElementType()->isIntegerTy())) && 2092 "Incorrect operand type (not integer) for S/UREM"); 2093 break; 2094 case FRem: 2095 assert(getType() == LHS->getType() && 2096 "Arithmetic operation should return same type as operands!"); 2097 assert(getType()->isFPOrFPVectorTy() && 2098 "Incorrect operand type (not floating point) for FREM"); 2099 break; 2100 case Shl: 2101 case LShr: 2102 case AShr: 2103 assert(getType() == LHS->getType() && 2104 "Shift operation should return same type as operands!"); 2105 assert((getType()->isIntegerTy() || 2106 (getType()->isVectorTy() && 2107 cast<VectorType>(getType())->getElementType()->isIntegerTy())) && 2108 "Tried to create a shift operation on a non-integral type!"); 2109 break; 2110 case And: case Or: 2111 case Xor: 2112 assert(getType() == LHS->getType() && 2113 "Logical operation should return same type as operands!"); 2114 assert((getType()->isIntegerTy() || 2115 (getType()->isVectorTy() && 2116 cast<VectorType>(getType())->getElementType()->isIntegerTy())) && 2117 "Tried to create a logical operation on a non-integral type!"); 2118 break; 2119 default: 2120 break; 2121 } 2122 #endif 2123 } 2124 2125 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 2126 const Twine &Name, 2127 Instruction *InsertBefore) { 2128 assert(S1->getType() == S2->getType() && 2129 "Cannot create binary operator with two operands of differing type!"); 2130 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore); 2131 } 2132 2133 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 2134 const Twine &Name, 2135 BasicBlock *InsertAtEnd) { 2136 BinaryOperator *Res = Create(Op, S1, S2, Name); 2137 InsertAtEnd->getInstList().push_back(Res); 2138 return Res; 2139 } 2140 2141 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 2142 Instruction *InsertBefore) { 2143 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2144 return new BinaryOperator(Instruction::Sub, 2145 zero, Op, 2146 Op->getType(), Name, InsertBefore); 2147 } 2148 2149 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 2150 BasicBlock *InsertAtEnd) { 2151 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2152 return new BinaryOperator(Instruction::Sub, 2153 zero, Op, 2154 Op->getType(), Name, InsertAtEnd); 2155 } 2156 2157 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, 2158 Instruction *InsertBefore) { 2159 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2160 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore); 2161 } 2162 2163 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, 2164 BasicBlock *InsertAtEnd) { 2165 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2166 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd); 2167 } 2168 2169 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, 2170 Instruction *InsertBefore) { 2171 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2172 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore); 2173 } 2174 2175 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, 2176 BasicBlock *InsertAtEnd) { 2177 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2178 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd); 2179 } 2180 2181 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name, 2182 Instruction *InsertBefore) { 2183 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2184 return new BinaryOperator(Instruction::FSub, zero, Op, 2185 Op->getType(), Name, InsertBefore); 2186 } 2187 2188 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name, 2189 BasicBlock *InsertAtEnd) { 2190 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2191 return new BinaryOperator(Instruction::FSub, zero, Op, 2192 Op->getType(), Name, InsertAtEnd); 2193 } 2194 2195 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 2196 Instruction *InsertBefore) { 2197 Constant *C = Constant::getAllOnesValue(Op->getType()); 2198 return new BinaryOperator(Instruction::Xor, Op, C, 2199 Op->getType(), Name, InsertBefore); 2200 } 2201 2202 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 2203 BasicBlock *InsertAtEnd) { 2204 Constant *AllOnes = Constant::getAllOnesValue(Op->getType()); 2205 return new BinaryOperator(Instruction::Xor, Op, AllOnes, 2206 Op->getType(), Name, InsertAtEnd); 2207 } 2208 2209 2210 // isConstantAllOnes - Helper function for several functions below 2211 static inline bool isConstantAllOnes(const Value *V) { 2212 if (const Constant *C = dyn_cast<Constant>(V)) 2213 return C->isAllOnesValue(); 2214 return false; 2215 } 2216 2217 bool BinaryOperator::isNeg(const Value *V) { 2218 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) 2219 if (Bop->getOpcode() == Instruction::Sub) 2220 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) 2221 return C->isNegativeZeroValue(); 2222 return false; 2223 } 2224 2225 bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) { 2226 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) 2227 if (Bop->getOpcode() == Instruction::FSub) 2228 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) { 2229 if (!IgnoreZeroSign) 2230 IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros(); 2231 return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue(); 2232 } 2233 return false; 2234 } 2235 2236 bool BinaryOperator::isNot(const Value *V) { 2237 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) 2238 return (Bop->getOpcode() == Instruction::Xor && 2239 (isConstantAllOnes(Bop->getOperand(1)) || 2240 isConstantAllOnes(Bop->getOperand(0)))); 2241 return false; 2242 } 2243 2244 Value *BinaryOperator::getNegArgument(Value *BinOp) { 2245 return cast<BinaryOperator>(BinOp)->getOperand(1); 2246 } 2247 2248 const Value *BinaryOperator::getNegArgument(const Value *BinOp) { 2249 return getNegArgument(const_cast<Value*>(BinOp)); 2250 } 2251 2252 Value *BinaryOperator::getFNegArgument(Value *BinOp) { 2253 return cast<BinaryOperator>(BinOp)->getOperand(1); 2254 } 2255 2256 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) { 2257 return getFNegArgument(const_cast<Value*>(BinOp)); 2258 } 2259 2260 Value *BinaryOperator::getNotArgument(Value *BinOp) { 2261 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!"); 2262 BinaryOperator *BO = cast<BinaryOperator>(BinOp); 2263 Value *Op0 = BO->getOperand(0); 2264 Value *Op1 = BO->getOperand(1); 2265 if (isConstantAllOnes(Op0)) return Op1; 2266 2267 assert(isConstantAllOnes(Op1)); 2268 return Op0; 2269 } 2270 2271 const Value *BinaryOperator::getNotArgument(const Value *BinOp) { 2272 return getNotArgument(const_cast<Value*>(BinOp)); 2273 } 2274 2275 2276 // swapOperands - Exchange the two operands to this instruction. This 2277 // instruction is safe to use on any binary instruction and does not 2278 // modify the semantics of the instruction. If the instruction is 2279 // order dependent (SetLT f.e.) the opcode is changed. 2280 // 2281 bool BinaryOperator::swapOperands() { 2282 if (!isCommutative()) 2283 return true; // Can't commute operands 2284 Op<0>().swap(Op<1>()); 2285 return false; 2286 } 2287 2288 void BinaryOperator::setHasNoUnsignedWrap(bool b) { 2289 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b); 2290 } 2291 2292 void BinaryOperator::setHasNoSignedWrap(bool b) { 2293 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b); 2294 } 2295 2296 void BinaryOperator::setIsExact(bool b) { 2297 cast<PossiblyExactOperator>(this)->setIsExact(b); 2298 } 2299 2300 bool BinaryOperator::hasNoUnsignedWrap() const { 2301 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap(); 2302 } 2303 2304 bool BinaryOperator::hasNoSignedWrap() const { 2305 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap(); 2306 } 2307 2308 bool BinaryOperator::isExact() const { 2309 return cast<PossiblyExactOperator>(this)->isExact(); 2310 } 2311 2312 void BinaryOperator::copyIRFlags(const Value *V) { 2313 // Copy the wrapping flags. 2314 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) { 2315 setHasNoSignedWrap(OB->hasNoSignedWrap()); 2316 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap()); 2317 } 2318 2319 // Copy the exact flag. 2320 if (auto *PE = dyn_cast<PossiblyExactOperator>(V)) 2321 setIsExact(PE->isExact()); 2322 2323 // Copy the fast-math flags. 2324 if (auto *FP = dyn_cast<FPMathOperator>(V)) 2325 copyFastMathFlags(FP->getFastMathFlags()); 2326 } 2327 2328 void BinaryOperator::andIRFlags(const Value *V) { 2329 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) { 2330 setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap()); 2331 setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap()); 2332 } 2333 2334 if (auto *PE = dyn_cast<PossiblyExactOperator>(V)) 2335 setIsExact(isExact() & PE->isExact()); 2336 2337 if (auto *FP = dyn_cast<FPMathOperator>(V)) { 2338 FastMathFlags FM = getFastMathFlags(); 2339 FM &= FP->getFastMathFlags(); 2340 copyFastMathFlags(FM); 2341 } 2342 } 2343 2344 2345 //===----------------------------------------------------------------------===// 2346 // FPMathOperator Class 2347 //===----------------------------------------------------------------------===// 2348 2349 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs. 2350 /// An accuracy of 0.0 means that the operation should be performed with the 2351 /// default precision. 2352 float FPMathOperator::getFPAccuracy() const { 2353 const MDNode *MD = 2354 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath); 2355 if (!MD) 2356 return 0.0; 2357 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0)); 2358 return Accuracy->getValueAPF().convertToFloat(); 2359 } 2360 2361 2362 //===----------------------------------------------------------------------===// 2363 // CastInst Class 2364 //===----------------------------------------------------------------------===// 2365 2366 void CastInst::anchor() {} 2367 2368 // Just determine if this cast only deals with integral->integral conversion. 2369 bool CastInst::isIntegerCast() const { 2370 switch (getOpcode()) { 2371 default: return false; 2372 case Instruction::ZExt: 2373 case Instruction::SExt: 2374 case Instruction::Trunc: 2375 return true; 2376 case Instruction::BitCast: 2377 return getOperand(0)->getType()->isIntegerTy() && 2378 getType()->isIntegerTy(); 2379 } 2380 } 2381 2382 bool CastInst::isLosslessCast() const { 2383 // Only BitCast can be lossless, exit fast if we're not BitCast 2384 if (getOpcode() != Instruction::BitCast) 2385 return false; 2386 2387 // Identity cast is always lossless 2388 Type* SrcTy = getOperand(0)->getType(); 2389 Type* DstTy = getType(); 2390 if (SrcTy == DstTy) 2391 return true; 2392 2393 // Pointer to pointer is always lossless. 2394 if (SrcTy->isPointerTy()) 2395 return DstTy->isPointerTy(); 2396 return false; // Other types have no identity values 2397 } 2398 2399 /// This function determines if the CastInst does not require any bits to be 2400 /// changed in order to effect the cast. Essentially, it identifies cases where 2401 /// no code gen is necessary for the cast, hence the name no-op cast. For 2402 /// example, the following are all no-op casts: 2403 /// # bitcast i32* %x to i8* 2404 /// # bitcast <2 x i32> %x to <4 x i16> 2405 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only 2406 /// @brief Determine if the described cast is a no-op. 2407 bool CastInst::isNoopCast(Instruction::CastOps Opcode, 2408 Type *SrcTy, 2409 Type *DestTy, 2410 Type *IntPtrTy) { 2411 switch (Opcode) { 2412 default: llvm_unreachable("Invalid CastOp"); 2413 case Instruction::Trunc: 2414 case Instruction::ZExt: 2415 case Instruction::SExt: 2416 case Instruction::FPTrunc: 2417 case Instruction::FPExt: 2418 case Instruction::UIToFP: 2419 case Instruction::SIToFP: 2420 case Instruction::FPToUI: 2421 case Instruction::FPToSI: 2422 case Instruction::AddrSpaceCast: 2423 // TODO: Target informations may give a more accurate answer here. 2424 return false; 2425 case Instruction::BitCast: 2426 return true; // BitCast never modifies bits. 2427 case Instruction::PtrToInt: 2428 return IntPtrTy->getScalarSizeInBits() == 2429 DestTy->getScalarSizeInBits(); 2430 case Instruction::IntToPtr: 2431 return IntPtrTy->getScalarSizeInBits() == 2432 SrcTy->getScalarSizeInBits(); 2433 } 2434 } 2435 2436 /// @brief Determine if a cast is a no-op. 2437 bool CastInst::isNoopCast(Type *IntPtrTy) const { 2438 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy); 2439 } 2440 2441 bool CastInst::isNoopCast(const DataLayout &DL) const { 2442 Type *PtrOpTy = nullptr; 2443 if (getOpcode() == Instruction::PtrToInt) 2444 PtrOpTy = getOperand(0)->getType(); 2445 else if (getOpcode() == Instruction::IntToPtr) 2446 PtrOpTy = getType(); 2447 2448 Type *IntPtrTy = 2449 PtrOpTy ? DL.getIntPtrType(PtrOpTy) : DL.getIntPtrType(getContext(), 0); 2450 2451 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy); 2452 } 2453 2454 /// This function determines if a pair of casts can be eliminated and what 2455 /// opcode should be used in the elimination. This assumes that there are two 2456 /// instructions like this: 2457 /// * %F = firstOpcode SrcTy %x to MidTy 2458 /// * %S = secondOpcode MidTy %F to DstTy 2459 /// The function returns a resultOpcode so these two casts can be replaced with: 2460 /// * %Replacement = resultOpcode %SrcTy %x to DstTy 2461 /// If no such cast is permited, the function returns 0. 2462 unsigned CastInst::isEliminableCastPair( 2463 Instruction::CastOps firstOp, Instruction::CastOps secondOp, 2464 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy, 2465 Type *DstIntPtrTy) { 2466 // Define the 144 possibilities for these two cast instructions. The values 2467 // in this matrix determine what to do in a given situation and select the 2468 // case in the switch below. The rows correspond to firstOp, the columns 2469 // correspond to secondOp. In looking at the table below, keep in mind 2470 // the following cast properties: 2471 // 2472 // Size Compare Source Destination 2473 // Operator Src ? Size Type Sign Type Sign 2474 // -------- ------------ ------------------- --------------------- 2475 // TRUNC > Integer Any Integral Any 2476 // ZEXT < Integral Unsigned Integer Any 2477 // SEXT < Integral Signed Integer Any 2478 // FPTOUI n/a FloatPt n/a Integral Unsigned 2479 // FPTOSI n/a FloatPt n/a Integral Signed 2480 // UITOFP n/a Integral Unsigned FloatPt n/a 2481 // SITOFP n/a Integral Signed FloatPt n/a 2482 // FPTRUNC > FloatPt n/a FloatPt n/a 2483 // FPEXT < FloatPt n/a FloatPt n/a 2484 // PTRTOINT n/a Pointer n/a Integral Unsigned 2485 // INTTOPTR n/a Integral Unsigned Pointer n/a 2486 // BITCAST = FirstClass n/a FirstClass n/a 2487 // ADDRSPCST n/a Pointer n/a Pointer n/a 2488 // 2489 // NOTE: some transforms are safe, but we consider them to be non-profitable. 2490 // For example, we could merge "fptoui double to i32" + "zext i32 to i64", 2491 // into "fptoui double to i64", but this loses information about the range 2492 // of the produced value (we no longer know the top-part is all zeros). 2493 // Further this conversion is often much more expensive for typical hardware, 2494 // and causes issues when building libgcc. We disallow fptosi+sext for the 2495 // same reason. 2496 const unsigned numCastOps = 2497 Instruction::CastOpsEnd - Instruction::CastOpsBegin; 2498 static const uint8_t CastResults[numCastOps][numCastOps] = { 2499 // T F F U S F F P I B A -+ 2500 // R Z S P P I I T P 2 N T S | 2501 // U E E 2 2 2 2 R E I T C C +- secondOp 2502 // N X X U S F F N X N 2 V V | 2503 // C T T I I P P C T T P T T -+ 2504 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+ 2505 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt | 2506 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt | 2507 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI | 2508 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI | 2509 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp 2510 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP | 2511 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc | 2512 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4, 0}, // FPExt | 2513 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt | 2514 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr | 2515 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast | 2516 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+ 2517 }; 2518 2519 // If either of the casts are a bitcast from scalar to vector, disallow the 2520 // merging. However, bitcast of A->B->A are allowed. 2521 bool isFirstBitcast = (firstOp == Instruction::BitCast); 2522 bool isSecondBitcast = (secondOp == Instruction::BitCast); 2523 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast); 2524 2525 // Check if any of the bitcasts convert scalars<->vectors. 2526 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) || 2527 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy))) 2528 // Unless we are bitcasing to the original type, disallow optimizations. 2529 if (!chainedBitcast) return 0; 2530 2531 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin] 2532 [secondOp-Instruction::CastOpsBegin]; 2533 switch (ElimCase) { 2534 case 0: 2535 // Categorically disallowed. 2536 return 0; 2537 case 1: 2538 // Allowed, use first cast's opcode. 2539 return firstOp; 2540 case 2: 2541 // Allowed, use second cast's opcode. 2542 return secondOp; 2543 case 3: 2544 // No-op cast in second op implies firstOp as long as the DestTy 2545 // is integer and we are not converting between a vector and a 2546 // non-vector type. 2547 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy()) 2548 return firstOp; 2549 return 0; 2550 case 4: 2551 // No-op cast in second op implies firstOp as long as the DestTy 2552 // is floating point. 2553 if (DstTy->isFloatingPointTy()) 2554 return firstOp; 2555 return 0; 2556 case 5: 2557 // No-op cast in first op implies secondOp as long as the SrcTy 2558 // is an integer. 2559 if (SrcTy->isIntegerTy()) 2560 return secondOp; 2561 return 0; 2562 case 6: 2563 // No-op cast in first op implies secondOp as long as the SrcTy 2564 // is a floating point. 2565 if (SrcTy->isFloatingPointTy()) 2566 return secondOp; 2567 return 0; 2568 case 7: { 2569 // Cannot simplify if address spaces are different! 2570 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) 2571 return 0; 2572 2573 unsigned MidSize = MidTy->getScalarSizeInBits(); 2574 // We can still fold this without knowing the actual sizes as long we 2575 // know that the intermediate pointer is the largest possible 2576 // pointer size. 2577 // FIXME: Is this always true? 2578 if (MidSize == 64) 2579 return Instruction::BitCast; 2580 2581 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size. 2582 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy) 2583 return 0; 2584 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits(); 2585 if (MidSize >= PtrSize) 2586 return Instruction::BitCast; 2587 return 0; 2588 } 2589 case 8: { 2590 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size 2591 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy) 2592 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy) 2593 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 2594 unsigned DstSize = DstTy->getScalarSizeInBits(); 2595 if (SrcSize == DstSize) 2596 return Instruction::BitCast; 2597 else if (SrcSize < DstSize) 2598 return firstOp; 2599 return secondOp; 2600 } 2601 case 9: 2602 // zext, sext -> zext, because sext can't sign extend after zext 2603 return Instruction::ZExt; 2604 case 10: 2605 // fpext followed by ftrunc is allowed if the bit size returned to is 2606 // the same as the original, in which case its just a bitcast 2607 if (SrcTy == DstTy) 2608 return Instruction::BitCast; 2609 return 0; // If the types are not the same we can't eliminate it. 2610 case 11: { 2611 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize 2612 if (!MidIntPtrTy) 2613 return 0; 2614 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits(); 2615 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 2616 unsigned DstSize = DstTy->getScalarSizeInBits(); 2617 if (SrcSize <= PtrSize && SrcSize == DstSize) 2618 return Instruction::BitCast; 2619 return 0; 2620 } 2621 case 12: { 2622 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS 2623 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS 2624 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) 2625 return Instruction::AddrSpaceCast; 2626 return Instruction::BitCast; 2627 } 2628 case 13: 2629 // FIXME: this state can be merged with (1), but the following assert 2630 // is useful to check the correcteness of the sequence due to semantic 2631 // change of bitcast. 2632 assert( 2633 SrcTy->isPtrOrPtrVectorTy() && 2634 MidTy->isPtrOrPtrVectorTy() && 2635 DstTy->isPtrOrPtrVectorTy() && 2636 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() && 2637 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && 2638 "Illegal addrspacecast, bitcast sequence!"); 2639 // Allowed, use first cast's opcode 2640 return firstOp; 2641 case 14: 2642 // bitcast, addrspacecast -> addrspacecast if the element type of 2643 // bitcast's source is the same as that of addrspacecast's destination. 2644 if (SrcTy->getPointerElementType() == DstTy->getPointerElementType()) 2645 return Instruction::AddrSpaceCast; 2646 return 0; 2647 2648 case 15: 2649 // FIXME: this state can be merged with (1), but the following assert 2650 // is useful to check the correcteness of the sequence due to semantic 2651 // change of bitcast. 2652 assert( 2653 SrcTy->isIntOrIntVectorTy() && 2654 MidTy->isPtrOrPtrVectorTy() && 2655 DstTy->isPtrOrPtrVectorTy() && 2656 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && 2657 "Illegal inttoptr, bitcast sequence!"); 2658 // Allowed, use first cast's opcode 2659 return firstOp; 2660 case 16: 2661 // FIXME: this state can be merged with (2), but the following assert 2662 // is useful to check the correcteness of the sequence due to semantic 2663 // change of bitcast. 2664 assert( 2665 SrcTy->isPtrOrPtrVectorTy() && 2666 MidTy->isPtrOrPtrVectorTy() && 2667 DstTy->isIntOrIntVectorTy() && 2668 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() && 2669 "Illegal bitcast, ptrtoint sequence!"); 2670 // Allowed, use second cast's opcode 2671 return secondOp; 2672 case 17: 2673 // (sitofp (zext x)) -> (uitofp x) 2674 return Instruction::UIToFP; 2675 case 99: 2676 // Cast combination can't happen (error in input). This is for all cases 2677 // where the MidTy is not the same for the two cast instructions. 2678 llvm_unreachable("Invalid Cast Combination"); 2679 default: 2680 llvm_unreachable("Error in CastResults table!!!"); 2681 } 2682 } 2683 2684 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 2685 const Twine &Name, Instruction *InsertBefore) { 2686 assert(castIsValid(op, S, Ty) && "Invalid cast!"); 2687 // Construct and return the appropriate CastInst subclass 2688 switch (op) { 2689 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore); 2690 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore); 2691 case SExt: return new SExtInst (S, Ty, Name, InsertBefore); 2692 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore); 2693 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore); 2694 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore); 2695 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore); 2696 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore); 2697 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore); 2698 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore); 2699 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore); 2700 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore); 2701 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore); 2702 default: llvm_unreachable("Invalid opcode provided"); 2703 } 2704 } 2705 2706 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 2707 const Twine &Name, BasicBlock *InsertAtEnd) { 2708 assert(castIsValid(op, S, Ty) && "Invalid cast!"); 2709 // Construct and return the appropriate CastInst subclass 2710 switch (op) { 2711 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd); 2712 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd); 2713 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd); 2714 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd); 2715 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd); 2716 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd); 2717 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd); 2718 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd); 2719 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd); 2720 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd); 2721 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd); 2722 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd); 2723 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd); 2724 default: llvm_unreachable("Invalid opcode provided"); 2725 } 2726 } 2727 2728 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 2729 const Twine &Name, 2730 Instruction *InsertBefore) { 2731 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2732 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2733 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore); 2734 } 2735 2736 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 2737 const Twine &Name, 2738 BasicBlock *InsertAtEnd) { 2739 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2740 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2741 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd); 2742 } 2743 2744 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 2745 const Twine &Name, 2746 Instruction *InsertBefore) { 2747 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2748 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2749 return Create(Instruction::SExt, S, Ty, Name, InsertBefore); 2750 } 2751 2752 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 2753 const Twine &Name, 2754 BasicBlock *InsertAtEnd) { 2755 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2756 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2757 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd); 2758 } 2759 2760 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, 2761 const Twine &Name, 2762 Instruction *InsertBefore) { 2763 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2764 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2765 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore); 2766 } 2767 2768 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, 2769 const Twine &Name, 2770 BasicBlock *InsertAtEnd) { 2771 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2772 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2773 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd); 2774 } 2775 2776 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 2777 const Twine &Name, 2778 BasicBlock *InsertAtEnd) { 2779 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2780 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 2781 "Invalid cast"); 2782 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); 2783 assert((!Ty->isVectorTy() || 2784 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) && 2785 "Invalid cast"); 2786 2787 if (Ty->isIntOrIntVectorTy()) 2788 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd); 2789 2790 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd); 2791 } 2792 2793 /// @brief Create a BitCast or a PtrToInt cast instruction 2794 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 2795 const Twine &Name, 2796 Instruction *InsertBefore) { 2797 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2798 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 2799 "Invalid cast"); 2800 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); 2801 assert((!Ty->isVectorTy() || 2802 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) && 2803 "Invalid cast"); 2804 2805 if (Ty->isIntOrIntVectorTy()) 2806 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 2807 2808 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore); 2809 } 2810 2811 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( 2812 Value *S, Type *Ty, 2813 const Twine &Name, 2814 BasicBlock *InsertAtEnd) { 2815 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2816 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 2817 2818 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 2819 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd); 2820 2821 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2822 } 2823 2824 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( 2825 Value *S, Type *Ty, 2826 const Twine &Name, 2827 Instruction *InsertBefore) { 2828 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2829 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 2830 2831 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 2832 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore); 2833 2834 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2835 } 2836 2837 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty, 2838 const Twine &Name, 2839 Instruction *InsertBefore) { 2840 if (S->getType()->isPointerTy() && Ty->isIntegerTy()) 2841 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 2842 if (S->getType()->isIntegerTy() && Ty->isPointerTy()) 2843 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore); 2844 2845 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2846 } 2847 2848 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 2849 bool isSigned, const Twine &Name, 2850 Instruction *InsertBefore) { 2851 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 2852 "Invalid integer cast"); 2853 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2854 unsigned DstBits = Ty->getScalarSizeInBits(); 2855 Instruction::CastOps opcode = 2856 (SrcBits == DstBits ? Instruction::BitCast : 2857 (SrcBits > DstBits ? Instruction::Trunc : 2858 (isSigned ? Instruction::SExt : Instruction::ZExt))); 2859 return Create(opcode, C, Ty, Name, InsertBefore); 2860 } 2861 2862 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 2863 bool isSigned, const Twine &Name, 2864 BasicBlock *InsertAtEnd) { 2865 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 2866 "Invalid cast"); 2867 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2868 unsigned DstBits = Ty->getScalarSizeInBits(); 2869 Instruction::CastOps opcode = 2870 (SrcBits == DstBits ? Instruction::BitCast : 2871 (SrcBits > DstBits ? Instruction::Trunc : 2872 (isSigned ? Instruction::SExt : Instruction::ZExt))); 2873 return Create(opcode, C, Ty, Name, InsertAtEnd); 2874 } 2875 2876 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 2877 const Twine &Name, 2878 Instruction *InsertBefore) { 2879 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 2880 "Invalid cast"); 2881 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2882 unsigned DstBits = Ty->getScalarSizeInBits(); 2883 Instruction::CastOps opcode = 2884 (SrcBits == DstBits ? Instruction::BitCast : 2885 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 2886 return Create(opcode, C, Ty, Name, InsertBefore); 2887 } 2888 2889 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 2890 const Twine &Name, 2891 BasicBlock *InsertAtEnd) { 2892 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 2893 "Invalid cast"); 2894 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2895 unsigned DstBits = Ty->getScalarSizeInBits(); 2896 Instruction::CastOps opcode = 2897 (SrcBits == DstBits ? Instruction::BitCast : 2898 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 2899 return Create(opcode, C, Ty, Name, InsertAtEnd); 2900 } 2901 2902 // Check whether it is valid to call getCastOpcode for these types. 2903 // This routine must be kept in sync with getCastOpcode. 2904 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) { 2905 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 2906 return false; 2907 2908 if (SrcTy == DestTy) 2909 return true; 2910 2911 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) 2912 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) 2913 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 2914 // An element by element cast. Valid if casting the elements is valid. 2915 SrcTy = SrcVecTy->getElementType(); 2916 DestTy = DestVecTy->getElementType(); 2917 } 2918 2919 // Get the bit sizes, we'll need these 2920 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 2921 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 2922 2923 // Run through the possibilities ... 2924 if (DestTy->isIntegerTy()) { // Casting to integral 2925 if (SrcTy->isIntegerTy()) // Casting from integral 2926 return true; 2927 if (SrcTy->isFloatingPointTy()) // Casting from floating pt 2928 return true; 2929 if (SrcTy->isVectorTy()) // Casting from vector 2930 return DestBits == SrcBits; 2931 // Casting from something else 2932 return SrcTy->isPointerTy(); 2933 } 2934 if (DestTy->isFloatingPointTy()) { // Casting to floating pt 2935 if (SrcTy->isIntegerTy()) // Casting from integral 2936 return true; 2937 if (SrcTy->isFloatingPointTy()) // Casting from floating pt 2938 return true; 2939 if (SrcTy->isVectorTy()) // Casting from vector 2940 return DestBits == SrcBits; 2941 // Casting from something else 2942 return false; 2943 } 2944 if (DestTy->isVectorTy()) // Casting to vector 2945 return DestBits == SrcBits; 2946 if (DestTy->isPointerTy()) { // Casting to pointer 2947 if (SrcTy->isPointerTy()) // Casting from pointer 2948 return true; 2949 return SrcTy->isIntegerTy(); // Casting from integral 2950 } 2951 if (DestTy->isX86_MMXTy()) { 2952 if (SrcTy->isVectorTy()) 2953 return DestBits == SrcBits; // 64-bit vector to MMX 2954 return false; 2955 } // Casting to something else 2956 return false; 2957 } 2958 2959 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) { 2960 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 2961 return false; 2962 2963 if (SrcTy == DestTy) 2964 return true; 2965 2966 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { 2967 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) { 2968 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 2969 // An element by element cast. Valid if casting the elements is valid. 2970 SrcTy = SrcVecTy->getElementType(); 2971 DestTy = DestVecTy->getElementType(); 2972 } 2973 } 2974 } 2975 2976 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) { 2977 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) { 2978 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace(); 2979 } 2980 } 2981 2982 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 2983 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 2984 2985 // Could still have vectors of pointers if the number of elements doesn't 2986 // match 2987 if (SrcBits == 0 || DestBits == 0) 2988 return false; 2989 2990 if (SrcBits != DestBits) 2991 return false; 2992 2993 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy()) 2994 return false; 2995 2996 return true; 2997 } 2998 2999 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, 3000 const DataLayout &DL) { 3001 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy)) 3002 if (auto *IntTy = dyn_cast<IntegerType>(DestTy)) 3003 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy); 3004 if (auto *PtrTy = dyn_cast<PointerType>(DestTy)) 3005 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy)) 3006 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy); 3007 3008 return isBitCastable(SrcTy, DestTy); 3009 } 3010 3011 // Provide a way to get a "cast" where the cast opcode is inferred from the 3012 // types and size of the operand. This, basically, is a parallel of the 3013 // logic in the castIsValid function below. This axiom should hold: 3014 // castIsValid( getCastOpcode(Val, Ty), Val, Ty) 3015 // should not assert in castIsValid. In other words, this produces a "correct" 3016 // casting opcode for the arguments passed to it. 3017 // This routine must be kept in sync with isCastable. 3018 Instruction::CastOps 3019 CastInst::getCastOpcode( 3020 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) { 3021 Type *SrcTy = Src->getType(); 3022 3023 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() && 3024 "Only first class types are castable!"); 3025 3026 if (SrcTy == DestTy) 3027 return BitCast; 3028 3029 // FIXME: Check address space sizes here 3030 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) 3031 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) 3032 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 3033 // An element by element cast. Find the appropriate opcode based on the 3034 // element types. 3035 SrcTy = SrcVecTy->getElementType(); 3036 DestTy = DestVecTy->getElementType(); 3037 } 3038 3039 // Get the bit sizes, we'll need these 3040 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 3041 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 3042 3043 // Run through the possibilities ... 3044 if (DestTy->isIntegerTy()) { // Casting to integral 3045 if (SrcTy->isIntegerTy()) { // Casting from integral 3046 if (DestBits < SrcBits) 3047 return Trunc; // int -> smaller int 3048 else if (DestBits > SrcBits) { // its an extension 3049 if (SrcIsSigned) 3050 return SExt; // signed -> SEXT 3051 else 3052 return ZExt; // unsigned -> ZEXT 3053 } else { 3054 return BitCast; // Same size, No-op cast 3055 } 3056 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt 3057 if (DestIsSigned) 3058 return FPToSI; // FP -> sint 3059 else 3060 return FPToUI; // FP -> uint 3061 } else if (SrcTy->isVectorTy()) { 3062 assert(DestBits == SrcBits && 3063 "Casting vector to integer of different width"); 3064 return BitCast; // Same size, no-op cast 3065 } else { 3066 assert(SrcTy->isPointerTy() && 3067 "Casting from a value that is not first-class type"); 3068 return PtrToInt; // ptr -> int 3069 } 3070 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt 3071 if (SrcTy->isIntegerTy()) { // Casting from integral 3072 if (SrcIsSigned) 3073 return SIToFP; // sint -> FP 3074 else 3075 return UIToFP; // uint -> FP 3076 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt 3077 if (DestBits < SrcBits) { 3078 return FPTrunc; // FP -> smaller FP 3079 } else if (DestBits > SrcBits) { 3080 return FPExt; // FP -> larger FP 3081 } else { 3082 return BitCast; // same size, no-op cast 3083 } 3084 } else if (SrcTy->isVectorTy()) { 3085 assert(DestBits == SrcBits && 3086 "Casting vector to floating point of different width"); 3087 return BitCast; // same size, no-op cast 3088 } 3089 llvm_unreachable("Casting pointer or non-first class to float"); 3090 } else if (DestTy->isVectorTy()) { 3091 assert(DestBits == SrcBits && 3092 "Illegal cast to vector (wrong type or size)"); 3093 return BitCast; 3094 } else if (DestTy->isPointerTy()) { 3095 if (SrcTy->isPointerTy()) { 3096 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace()) 3097 return AddrSpaceCast; 3098 return BitCast; // ptr -> ptr 3099 } else if (SrcTy->isIntegerTy()) { 3100 return IntToPtr; // int -> ptr 3101 } 3102 llvm_unreachable("Casting pointer to other than pointer or int"); 3103 } else if (DestTy->isX86_MMXTy()) { 3104 if (SrcTy->isVectorTy()) { 3105 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX"); 3106 return BitCast; // 64-bit vector to MMX 3107 } 3108 llvm_unreachable("Illegal cast to X86_MMX"); 3109 } 3110 llvm_unreachable("Casting to type that is not first-class"); 3111 } 3112 3113 //===----------------------------------------------------------------------===// 3114 // CastInst SubClass Constructors 3115 //===----------------------------------------------------------------------===// 3116 3117 /// Check that the construction parameters for a CastInst are correct. This 3118 /// could be broken out into the separate constructors but it is useful to have 3119 /// it in one place and to eliminate the redundant code for getting the sizes 3120 /// of the types involved. 3121 bool 3122 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) { 3123 3124 // Check for type sanity on the arguments 3125 Type *SrcTy = S->getType(); 3126 3127 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() || 3128 SrcTy->isAggregateType() || DstTy->isAggregateType()) 3129 return false; 3130 3131 // Get the size of the types in bits, we'll need this later 3132 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 3133 unsigned DstBitSize = DstTy->getScalarSizeInBits(); 3134 3135 // If these are vector types, get the lengths of the vectors (using zero for 3136 // scalar types means that checking that vector lengths match also checks that 3137 // scalars are not being converted to vectors or vectors to scalars). 3138 unsigned SrcLength = SrcTy->isVectorTy() ? 3139 cast<VectorType>(SrcTy)->getNumElements() : 0; 3140 unsigned DstLength = DstTy->isVectorTy() ? 3141 cast<VectorType>(DstTy)->getNumElements() : 0; 3142 3143 // Switch on the opcode provided 3144 switch (op) { 3145 default: return false; // This is an input error 3146 case Instruction::Trunc: 3147 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3148 SrcLength == DstLength && SrcBitSize > DstBitSize; 3149 case Instruction::ZExt: 3150 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3151 SrcLength == DstLength && SrcBitSize < DstBitSize; 3152 case Instruction::SExt: 3153 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3154 SrcLength == DstLength && SrcBitSize < DstBitSize; 3155 case Instruction::FPTrunc: 3156 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && 3157 SrcLength == DstLength && SrcBitSize > DstBitSize; 3158 case Instruction::FPExt: 3159 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && 3160 SrcLength == DstLength && SrcBitSize < DstBitSize; 3161 case Instruction::UIToFP: 3162 case Instruction::SIToFP: 3163 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() && 3164 SrcLength == DstLength; 3165 case Instruction::FPToUI: 3166 case Instruction::FPToSI: 3167 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() && 3168 SrcLength == DstLength; 3169 case Instruction::PtrToInt: 3170 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy)) 3171 return false; 3172 if (VectorType *VT = dyn_cast<VectorType>(SrcTy)) 3173 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements()) 3174 return false; 3175 return SrcTy->getScalarType()->isPointerTy() && 3176 DstTy->getScalarType()->isIntegerTy(); 3177 case Instruction::IntToPtr: 3178 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy)) 3179 return false; 3180 if (VectorType *VT = dyn_cast<VectorType>(SrcTy)) 3181 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements()) 3182 return false; 3183 return SrcTy->getScalarType()->isIntegerTy() && 3184 DstTy->getScalarType()->isPointerTy(); 3185 case Instruction::BitCast: { 3186 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); 3187 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); 3188 3189 // BitCast implies a no-op cast of type only. No bits change. 3190 // However, you can't cast pointers to anything but pointers. 3191 if (!SrcPtrTy != !DstPtrTy) 3192 return false; 3193 3194 // For non-pointer cases, the cast is okay if the source and destination bit 3195 // widths are identical. 3196 if (!SrcPtrTy) 3197 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits(); 3198 3199 // If both are pointers then the address spaces must match. 3200 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) 3201 return false; 3202 3203 // A vector of pointers must have the same number of elements. 3204 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { 3205 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy)) 3206 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements()); 3207 3208 return false; 3209 } 3210 3211 return true; 3212 } 3213 case Instruction::AddrSpaceCast: { 3214 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); 3215 if (!SrcPtrTy) 3216 return false; 3217 3218 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); 3219 if (!DstPtrTy) 3220 return false; 3221 3222 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace()) 3223 return false; 3224 3225 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { 3226 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy)) 3227 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements()); 3228 3229 return false; 3230 } 3231 3232 return true; 3233 } 3234 } 3235 } 3236 3237 TruncInst::TruncInst( 3238 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3239 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) { 3240 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 3241 } 3242 3243 TruncInst::TruncInst( 3244 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3245 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 3246 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 3247 } 3248 3249 ZExtInst::ZExtInst( 3250 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3251 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) { 3252 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 3253 } 3254 3255 ZExtInst::ZExtInst( 3256 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3257 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 3258 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 3259 } 3260 SExtInst::SExtInst( 3261 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3262 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 3263 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 3264 } 3265 3266 SExtInst::SExtInst( 3267 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3268 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 3269 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 3270 } 3271 3272 FPTruncInst::FPTruncInst( 3273 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3274 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 3275 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 3276 } 3277 3278 FPTruncInst::FPTruncInst( 3279 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3280 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 3281 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 3282 } 3283 3284 FPExtInst::FPExtInst( 3285 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3286 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 3287 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 3288 } 3289 3290 FPExtInst::FPExtInst( 3291 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3292 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 3293 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 3294 } 3295 3296 UIToFPInst::UIToFPInst( 3297 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3298 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 3299 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 3300 } 3301 3302 UIToFPInst::UIToFPInst( 3303 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3304 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 3305 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 3306 } 3307 3308 SIToFPInst::SIToFPInst( 3309 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3310 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 3311 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 3312 } 3313 3314 SIToFPInst::SIToFPInst( 3315 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3316 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 3317 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 3318 } 3319 3320 FPToUIInst::FPToUIInst( 3321 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3322 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 3323 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 3324 } 3325 3326 FPToUIInst::FPToUIInst( 3327 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3328 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 3329 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 3330 } 3331 3332 FPToSIInst::FPToSIInst( 3333 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3334 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 3335 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 3336 } 3337 3338 FPToSIInst::FPToSIInst( 3339 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3340 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 3341 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 3342 } 3343 3344 PtrToIntInst::PtrToIntInst( 3345 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3346 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 3347 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 3348 } 3349 3350 PtrToIntInst::PtrToIntInst( 3351 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3352 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 3353 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 3354 } 3355 3356 IntToPtrInst::IntToPtrInst( 3357 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3358 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 3359 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 3360 } 3361 3362 IntToPtrInst::IntToPtrInst( 3363 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3364 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 3365 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 3366 } 3367 3368 BitCastInst::BitCastInst( 3369 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3370 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 3371 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 3372 } 3373 3374 BitCastInst::BitCastInst( 3375 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3376 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 3377 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 3378 } 3379 3380 AddrSpaceCastInst::AddrSpaceCastInst( 3381 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3382 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) { 3383 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); 3384 } 3385 3386 AddrSpaceCastInst::AddrSpaceCastInst( 3387 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3388 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) { 3389 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); 3390 } 3391 3392 //===----------------------------------------------------------------------===// 3393 // CmpInst Classes 3394 //===----------------------------------------------------------------------===// 3395 3396 void CmpInst::anchor() {} 3397 3398 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate, 3399 Value *LHS, Value *RHS, const Twine &Name, 3400 Instruction *InsertBefore) 3401 : Instruction(ty, op, 3402 OperandTraits<CmpInst>::op_begin(this), 3403 OperandTraits<CmpInst>::operands(this), 3404 InsertBefore) { 3405 Op<0>() = LHS; 3406 Op<1>() = RHS; 3407 setPredicate((Predicate)predicate); 3408 setName(Name); 3409 } 3410 3411 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate, 3412 Value *LHS, Value *RHS, const Twine &Name, 3413 BasicBlock *InsertAtEnd) 3414 : Instruction(ty, op, 3415 OperandTraits<CmpInst>::op_begin(this), 3416 OperandTraits<CmpInst>::operands(this), 3417 InsertAtEnd) { 3418 Op<0>() = LHS; 3419 Op<1>() = RHS; 3420 setPredicate((Predicate)predicate); 3421 setName(Name); 3422 } 3423 3424 CmpInst * 3425 CmpInst::Create(OtherOps Op, unsigned short predicate, 3426 Value *S1, Value *S2, 3427 const Twine &Name, Instruction *InsertBefore) { 3428 if (Op == Instruction::ICmp) { 3429 if (InsertBefore) 3430 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate), 3431 S1, S2, Name); 3432 else 3433 return new ICmpInst(CmpInst::Predicate(predicate), 3434 S1, S2, Name); 3435 } 3436 3437 if (InsertBefore) 3438 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate), 3439 S1, S2, Name); 3440 else 3441 return new FCmpInst(CmpInst::Predicate(predicate), 3442 S1, S2, Name); 3443 } 3444 3445 CmpInst * 3446 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 3447 const Twine &Name, BasicBlock *InsertAtEnd) { 3448 if (Op == Instruction::ICmp) { 3449 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 3450 S1, S2, Name); 3451 } 3452 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 3453 S1, S2, Name); 3454 } 3455 3456 void CmpInst::swapOperands() { 3457 if (ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3458 IC->swapOperands(); 3459 else 3460 cast<FCmpInst>(this)->swapOperands(); 3461 } 3462 3463 bool CmpInst::isCommutative() const { 3464 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3465 return IC->isCommutative(); 3466 return cast<FCmpInst>(this)->isCommutative(); 3467 } 3468 3469 bool CmpInst::isEquality() const { 3470 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3471 return IC->isEquality(); 3472 return cast<FCmpInst>(this)->isEquality(); 3473 } 3474 3475 3476 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) { 3477 switch (pred) { 3478 default: llvm_unreachable("Unknown cmp predicate!"); 3479 case ICMP_EQ: return ICMP_NE; 3480 case ICMP_NE: return ICMP_EQ; 3481 case ICMP_UGT: return ICMP_ULE; 3482 case ICMP_ULT: return ICMP_UGE; 3483 case ICMP_UGE: return ICMP_ULT; 3484 case ICMP_ULE: return ICMP_UGT; 3485 case ICMP_SGT: return ICMP_SLE; 3486 case ICMP_SLT: return ICMP_SGE; 3487 case ICMP_SGE: return ICMP_SLT; 3488 case ICMP_SLE: return ICMP_SGT; 3489 3490 case FCMP_OEQ: return FCMP_UNE; 3491 case FCMP_ONE: return FCMP_UEQ; 3492 case FCMP_OGT: return FCMP_ULE; 3493 case FCMP_OLT: return FCMP_UGE; 3494 case FCMP_OGE: return FCMP_ULT; 3495 case FCMP_OLE: return FCMP_UGT; 3496 case FCMP_UEQ: return FCMP_ONE; 3497 case FCMP_UNE: return FCMP_OEQ; 3498 case FCMP_UGT: return FCMP_OLE; 3499 case FCMP_ULT: return FCMP_OGE; 3500 case FCMP_UGE: return FCMP_OLT; 3501 case FCMP_ULE: return FCMP_OGT; 3502 case FCMP_ORD: return FCMP_UNO; 3503 case FCMP_UNO: return FCMP_ORD; 3504 case FCMP_TRUE: return FCMP_FALSE; 3505 case FCMP_FALSE: return FCMP_TRUE; 3506 } 3507 } 3508 3509 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) { 3510 switch (pred) { 3511 default: llvm_unreachable("Unknown icmp predicate!"); 3512 case ICMP_EQ: case ICMP_NE: 3513 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 3514 return pred; 3515 case ICMP_UGT: return ICMP_SGT; 3516 case ICMP_ULT: return ICMP_SLT; 3517 case ICMP_UGE: return ICMP_SGE; 3518 case ICMP_ULE: return ICMP_SLE; 3519 } 3520 } 3521 3522 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) { 3523 switch (pred) { 3524 default: llvm_unreachable("Unknown icmp predicate!"); 3525 case ICMP_EQ: case ICMP_NE: 3526 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 3527 return pred; 3528 case ICMP_SGT: return ICMP_UGT; 3529 case ICMP_SLT: return ICMP_ULT; 3530 case ICMP_SGE: return ICMP_UGE; 3531 case ICMP_SLE: return ICMP_ULE; 3532 } 3533 } 3534 3535 /// Initialize a set of values that all satisfy the condition with C. 3536 /// 3537 ConstantRange 3538 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) { 3539 APInt Lower(C); 3540 APInt Upper(C); 3541 uint32_t BitWidth = C.getBitWidth(); 3542 switch (pred) { 3543 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!"); 3544 case ICmpInst::ICMP_EQ: ++Upper; break; 3545 case ICmpInst::ICMP_NE: ++Lower; break; 3546 case ICmpInst::ICMP_ULT: 3547 Lower = APInt::getMinValue(BitWidth); 3548 // Check for an empty-set condition. 3549 if (Lower == Upper) 3550 return ConstantRange(BitWidth, /*isFullSet=*/false); 3551 break; 3552 case ICmpInst::ICMP_SLT: 3553 Lower = APInt::getSignedMinValue(BitWidth); 3554 // Check for an empty-set condition. 3555 if (Lower == Upper) 3556 return ConstantRange(BitWidth, /*isFullSet=*/false); 3557 break; 3558 case ICmpInst::ICMP_UGT: 3559 ++Lower; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max) 3560 // Check for an empty-set condition. 3561 if (Lower == Upper) 3562 return ConstantRange(BitWidth, /*isFullSet=*/false); 3563 break; 3564 case ICmpInst::ICMP_SGT: 3565 ++Lower; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max) 3566 // Check for an empty-set condition. 3567 if (Lower == Upper) 3568 return ConstantRange(BitWidth, /*isFullSet=*/false); 3569 break; 3570 case ICmpInst::ICMP_ULE: 3571 Lower = APInt::getMinValue(BitWidth); ++Upper; 3572 // Check for a full-set condition. 3573 if (Lower == Upper) 3574 return ConstantRange(BitWidth, /*isFullSet=*/true); 3575 break; 3576 case ICmpInst::ICMP_SLE: 3577 Lower = APInt::getSignedMinValue(BitWidth); ++Upper; 3578 // Check for a full-set condition. 3579 if (Lower == Upper) 3580 return ConstantRange(BitWidth, /*isFullSet=*/true); 3581 break; 3582 case ICmpInst::ICMP_UGE: 3583 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max) 3584 // Check for a full-set condition. 3585 if (Lower == Upper) 3586 return ConstantRange(BitWidth, /*isFullSet=*/true); 3587 break; 3588 case ICmpInst::ICMP_SGE: 3589 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max) 3590 // Check for a full-set condition. 3591 if (Lower == Upper) 3592 return ConstantRange(BitWidth, /*isFullSet=*/true); 3593 break; 3594 } 3595 return ConstantRange(Lower, Upper); 3596 } 3597 3598 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) { 3599 switch (pred) { 3600 default: llvm_unreachable("Unknown cmp predicate!"); 3601 case ICMP_EQ: case ICMP_NE: 3602 return pred; 3603 case ICMP_SGT: return ICMP_SLT; 3604 case ICMP_SLT: return ICMP_SGT; 3605 case ICMP_SGE: return ICMP_SLE; 3606 case ICMP_SLE: return ICMP_SGE; 3607 case ICMP_UGT: return ICMP_ULT; 3608 case ICMP_ULT: return ICMP_UGT; 3609 case ICMP_UGE: return ICMP_ULE; 3610 case ICMP_ULE: return ICMP_UGE; 3611 3612 case FCMP_FALSE: case FCMP_TRUE: 3613 case FCMP_OEQ: case FCMP_ONE: 3614 case FCMP_UEQ: case FCMP_UNE: 3615 case FCMP_ORD: case FCMP_UNO: 3616 return pred; 3617 case FCMP_OGT: return FCMP_OLT; 3618 case FCMP_OLT: return FCMP_OGT; 3619 case FCMP_OGE: return FCMP_OLE; 3620 case FCMP_OLE: return FCMP_OGE; 3621 case FCMP_UGT: return FCMP_ULT; 3622 case FCMP_ULT: return FCMP_UGT; 3623 case FCMP_UGE: return FCMP_ULE; 3624 case FCMP_ULE: return FCMP_UGE; 3625 } 3626 } 3627 3628 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) { 3629 assert(CmpInst::isUnsigned(pred) && "Call only with signed predicates!"); 3630 3631 switch (pred) { 3632 default: 3633 llvm_unreachable("Unknown predicate!"); 3634 case CmpInst::ICMP_ULT: 3635 return CmpInst::ICMP_SLT; 3636 case CmpInst::ICMP_ULE: 3637 return CmpInst::ICMP_SLE; 3638 case CmpInst::ICMP_UGT: 3639 return CmpInst::ICMP_SGT; 3640 case CmpInst::ICMP_UGE: 3641 return CmpInst::ICMP_SGE; 3642 } 3643 } 3644 3645 bool CmpInst::isUnsigned(unsigned short predicate) { 3646 switch (predicate) { 3647 default: return false; 3648 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 3649 case ICmpInst::ICMP_UGE: return true; 3650 } 3651 } 3652 3653 bool CmpInst::isSigned(unsigned short predicate) { 3654 switch (predicate) { 3655 default: return false; 3656 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 3657 case ICmpInst::ICMP_SGE: return true; 3658 } 3659 } 3660 3661 bool CmpInst::isOrdered(unsigned short predicate) { 3662 switch (predicate) { 3663 default: return false; 3664 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 3665 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 3666 case FCmpInst::FCMP_ORD: return true; 3667 } 3668 } 3669 3670 bool CmpInst::isUnordered(unsigned short predicate) { 3671 switch (predicate) { 3672 default: return false; 3673 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 3674 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 3675 case FCmpInst::FCMP_UNO: return true; 3676 } 3677 } 3678 3679 bool CmpInst::isTrueWhenEqual(unsigned short predicate) { 3680 switch(predicate) { 3681 default: return false; 3682 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE: 3683 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true; 3684 } 3685 } 3686 3687 bool CmpInst::isFalseWhenEqual(unsigned short predicate) { 3688 switch(predicate) { 3689 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT: 3690 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true; 3691 default: return false; 3692 } 3693 } 3694 3695 3696 //===----------------------------------------------------------------------===// 3697 // SwitchInst Implementation 3698 //===----------------------------------------------------------------------===// 3699 3700 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) { 3701 assert(Value && Default && NumReserved); 3702 ReservedSpace = NumReserved; 3703 setNumHungOffUseOperands(2); 3704 allocHungoffUses(ReservedSpace); 3705 3706 Op<0>() = Value; 3707 Op<1>() = Default; 3708 } 3709 3710 /// SwitchInst ctor - Create a new switch instruction, specifying a value to 3711 /// switch on and a default destination. The number of additional cases can 3712 /// be specified here to make memory allocation more efficient. This 3713 /// constructor can also autoinsert before another instruction. 3714 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 3715 Instruction *InsertBefore) 3716 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch, 3717 nullptr, 0, InsertBefore) { 3718 init(Value, Default, 2+NumCases*2); 3719 } 3720 3721 /// SwitchInst ctor - Create a new switch instruction, specifying a value to 3722 /// switch on and a default destination. The number of additional cases can 3723 /// be specified here to make memory allocation more efficient. This 3724 /// constructor also autoinserts at the end of the specified BasicBlock. 3725 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 3726 BasicBlock *InsertAtEnd) 3727 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch, 3728 nullptr, 0, InsertAtEnd) { 3729 init(Value, Default, 2+NumCases*2); 3730 } 3731 3732 SwitchInst::SwitchInst(const SwitchInst &SI) 3733 : TerminatorInst(SI.getType(), Instruction::Switch, nullptr, 0) { 3734 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands()); 3735 setNumHungOffUseOperands(SI.getNumOperands()); 3736 Use *OL = getOperandList(); 3737 const Use *InOL = SI.getOperandList(); 3738 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) { 3739 OL[i] = InOL[i]; 3740 OL[i+1] = InOL[i+1]; 3741 } 3742 SubclassOptionalData = SI.SubclassOptionalData; 3743 } 3744 3745 3746 /// addCase - Add an entry to the switch instruction... 3747 /// 3748 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) { 3749 unsigned NewCaseIdx = getNumCases(); 3750 unsigned OpNo = getNumOperands(); 3751 if (OpNo+2 > ReservedSpace) 3752 growOperands(); // Get more space! 3753 // Initialize some new operands. 3754 assert(OpNo+1 < ReservedSpace && "Growing didn't work!"); 3755 setNumHungOffUseOperands(OpNo+2); 3756 CaseIt Case(this, NewCaseIdx); 3757 Case.setValue(OnVal); 3758 Case.setSuccessor(Dest); 3759 } 3760 3761 /// removeCase - This method removes the specified case and its successor 3762 /// from the switch instruction. 3763 void SwitchInst::removeCase(CaseIt i) { 3764 unsigned idx = i.getCaseIndex(); 3765 3766 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!"); 3767 3768 unsigned NumOps = getNumOperands(); 3769 Use *OL = getOperandList(); 3770 3771 // Overwrite this case with the end of the list. 3772 if (2 + (idx + 1) * 2 != NumOps) { 3773 OL[2 + idx * 2] = OL[NumOps - 2]; 3774 OL[2 + idx * 2 + 1] = OL[NumOps - 1]; 3775 } 3776 3777 // Nuke the last value. 3778 OL[NumOps-2].set(nullptr); 3779 OL[NumOps-2+1].set(nullptr); 3780 setNumHungOffUseOperands(NumOps-2); 3781 } 3782 3783 /// growOperands - grow operands - This grows the operand list in response 3784 /// to a push_back style of operation. This grows the number of ops by 3 times. 3785 /// 3786 void SwitchInst::growOperands() { 3787 unsigned e = getNumOperands(); 3788 unsigned NumOps = e*3; 3789 3790 ReservedSpace = NumOps; 3791 growHungoffUses(ReservedSpace); 3792 } 3793 3794 3795 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const { 3796 return getSuccessor(idx); 3797 } 3798 unsigned SwitchInst::getNumSuccessorsV() const { 3799 return getNumSuccessors(); 3800 } 3801 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) { 3802 setSuccessor(idx, B); 3803 } 3804 3805 //===----------------------------------------------------------------------===// 3806 // IndirectBrInst Implementation 3807 //===----------------------------------------------------------------------===// 3808 3809 void IndirectBrInst::init(Value *Address, unsigned NumDests) { 3810 assert(Address && Address->getType()->isPointerTy() && 3811 "Address of indirectbr must be a pointer"); 3812 ReservedSpace = 1+NumDests; 3813 setNumHungOffUseOperands(1); 3814 allocHungoffUses(ReservedSpace); 3815 3816 Op<0>() = Address; 3817 } 3818 3819 3820 /// growOperands - grow operands - This grows the operand list in response 3821 /// to a push_back style of operation. This grows the number of ops by 2 times. 3822 /// 3823 void IndirectBrInst::growOperands() { 3824 unsigned e = getNumOperands(); 3825 unsigned NumOps = e*2; 3826 3827 ReservedSpace = NumOps; 3828 growHungoffUses(ReservedSpace); 3829 } 3830 3831 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, 3832 Instruction *InsertBefore) 3833 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr, 3834 nullptr, 0, InsertBefore) { 3835 init(Address, NumCases); 3836 } 3837 3838 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, 3839 BasicBlock *InsertAtEnd) 3840 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr, 3841 nullptr, 0, InsertAtEnd) { 3842 init(Address, NumCases); 3843 } 3844 3845 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI) 3846 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr, 3847 nullptr, IBI.getNumOperands()) { 3848 allocHungoffUses(IBI.getNumOperands()); 3849 Use *OL = getOperandList(); 3850 const Use *InOL = IBI.getOperandList(); 3851 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i) 3852 OL[i] = InOL[i]; 3853 SubclassOptionalData = IBI.SubclassOptionalData; 3854 } 3855 3856 /// addDestination - Add a destination. 3857 /// 3858 void IndirectBrInst::addDestination(BasicBlock *DestBB) { 3859 unsigned OpNo = getNumOperands(); 3860 if (OpNo+1 > ReservedSpace) 3861 growOperands(); // Get more space! 3862 // Initialize some new operands. 3863 assert(OpNo < ReservedSpace && "Growing didn't work!"); 3864 setNumHungOffUseOperands(OpNo+1); 3865 getOperandList()[OpNo] = DestBB; 3866 } 3867 3868 /// removeDestination - This method removes the specified successor from the 3869 /// indirectbr instruction. 3870 void IndirectBrInst::removeDestination(unsigned idx) { 3871 assert(idx < getNumOperands()-1 && "Successor index out of range!"); 3872 3873 unsigned NumOps = getNumOperands(); 3874 Use *OL = getOperandList(); 3875 3876 // Replace this value with the last one. 3877 OL[idx+1] = OL[NumOps-1]; 3878 3879 // Nuke the last value. 3880 OL[NumOps-1].set(nullptr); 3881 setNumHungOffUseOperands(NumOps-1); 3882 } 3883 3884 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const { 3885 return getSuccessor(idx); 3886 } 3887 unsigned IndirectBrInst::getNumSuccessorsV() const { 3888 return getNumSuccessors(); 3889 } 3890 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) { 3891 setSuccessor(idx, B); 3892 } 3893 3894 //===----------------------------------------------------------------------===// 3895 // cloneImpl() implementations 3896 //===----------------------------------------------------------------------===// 3897 3898 // Define these methods here so vtables don't get emitted into every translation 3899 // unit that uses these classes. 3900 3901 GetElementPtrInst *GetElementPtrInst::cloneImpl() const { 3902 return new (getNumOperands()) GetElementPtrInst(*this); 3903 } 3904 3905 BinaryOperator *BinaryOperator::cloneImpl() const { 3906 return Create(getOpcode(), Op<0>(), Op<1>()); 3907 } 3908 3909 FCmpInst *FCmpInst::cloneImpl() const { 3910 return new FCmpInst(getPredicate(), Op<0>(), Op<1>()); 3911 } 3912 3913 ICmpInst *ICmpInst::cloneImpl() const { 3914 return new ICmpInst(getPredicate(), Op<0>(), Op<1>()); 3915 } 3916 3917 ExtractValueInst *ExtractValueInst::cloneImpl() const { 3918 return new ExtractValueInst(*this); 3919 } 3920 3921 InsertValueInst *InsertValueInst::cloneImpl() const { 3922 return new InsertValueInst(*this); 3923 } 3924 3925 AllocaInst *AllocaInst::cloneImpl() const { 3926 AllocaInst *Result = new AllocaInst(getAllocatedType(), 3927 (Value *)getOperand(0), getAlignment()); 3928 Result->setUsedWithInAlloca(isUsedWithInAlloca()); 3929 return Result; 3930 } 3931 3932 LoadInst *LoadInst::cloneImpl() const { 3933 return new LoadInst(getOperand(0), Twine(), isVolatile(), 3934 getAlignment(), getOrdering(), getSynchScope()); 3935 } 3936 3937 StoreInst *StoreInst::cloneImpl() const { 3938 return new StoreInst(getOperand(0), getOperand(1), isVolatile(), 3939 getAlignment(), getOrdering(), getSynchScope()); 3940 3941 } 3942 3943 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const { 3944 AtomicCmpXchgInst *Result = 3945 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2), 3946 getSuccessOrdering(), getFailureOrdering(), 3947 getSynchScope()); 3948 Result->setVolatile(isVolatile()); 3949 Result->setWeak(isWeak()); 3950 return Result; 3951 } 3952 3953 AtomicRMWInst *AtomicRMWInst::cloneImpl() const { 3954 AtomicRMWInst *Result = 3955 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1), 3956 getOrdering(), getSynchScope()); 3957 Result->setVolatile(isVolatile()); 3958 return Result; 3959 } 3960 3961 FenceInst *FenceInst::cloneImpl() const { 3962 return new FenceInst(getContext(), getOrdering(), getSynchScope()); 3963 } 3964 3965 TruncInst *TruncInst::cloneImpl() const { 3966 return new TruncInst(getOperand(0), getType()); 3967 } 3968 3969 ZExtInst *ZExtInst::cloneImpl() const { 3970 return new ZExtInst(getOperand(0), getType()); 3971 } 3972 3973 SExtInst *SExtInst::cloneImpl() const { 3974 return new SExtInst(getOperand(0), getType()); 3975 } 3976 3977 FPTruncInst *FPTruncInst::cloneImpl() const { 3978 return new FPTruncInst(getOperand(0), getType()); 3979 } 3980 3981 FPExtInst *FPExtInst::cloneImpl() const { 3982 return new FPExtInst(getOperand(0), getType()); 3983 } 3984 3985 UIToFPInst *UIToFPInst::cloneImpl() const { 3986 return new UIToFPInst(getOperand(0), getType()); 3987 } 3988 3989 SIToFPInst *SIToFPInst::cloneImpl() const { 3990 return new SIToFPInst(getOperand(0), getType()); 3991 } 3992 3993 FPToUIInst *FPToUIInst::cloneImpl() const { 3994 return new FPToUIInst(getOperand(0), getType()); 3995 } 3996 3997 FPToSIInst *FPToSIInst::cloneImpl() const { 3998 return new FPToSIInst(getOperand(0), getType()); 3999 } 4000 4001 PtrToIntInst *PtrToIntInst::cloneImpl() const { 4002 return new PtrToIntInst(getOperand(0), getType()); 4003 } 4004 4005 IntToPtrInst *IntToPtrInst::cloneImpl() const { 4006 return new IntToPtrInst(getOperand(0), getType()); 4007 } 4008 4009 BitCastInst *BitCastInst::cloneImpl() const { 4010 return new BitCastInst(getOperand(0), getType()); 4011 } 4012 4013 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const { 4014 return new AddrSpaceCastInst(getOperand(0), getType()); 4015 } 4016 4017 CallInst *CallInst::cloneImpl() const { 4018 if (hasOperandBundles()) { 4019 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4020 return new(getNumOperands(), DescriptorBytes) CallInst(*this); 4021 } 4022 return new(getNumOperands()) CallInst(*this); 4023 } 4024 4025 SelectInst *SelectInst::cloneImpl() const { 4026 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2)); 4027 } 4028 4029 VAArgInst *VAArgInst::cloneImpl() const { 4030 return new VAArgInst(getOperand(0), getType()); 4031 } 4032 4033 ExtractElementInst *ExtractElementInst::cloneImpl() const { 4034 return ExtractElementInst::Create(getOperand(0), getOperand(1)); 4035 } 4036 4037 InsertElementInst *InsertElementInst::cloneImpl() const { 4038 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2)); 4039 } 4040 4041 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const { 4042 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2)); 4043 } 4044 4045 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); } 4046 4047 LandingPadInst *LandingPadInst::cloneImpl() const { 4048 return new LandingPadInst(*this); 4049 } 4050 4051 ReturnInst *ReturnInst::cloneImpl() const { 4052 return new(getNumOperands()) ReturnInst(*this); 4053 } 4054 4055 BranchInst *BranchInst::cloneImpl() const { 4056 return new(getNumOperands()) BranchInst(*this); 4057 } 4058 4059 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); } 4060 4061 IndirectBrInst *IndirectBrInst::cloneImpl() const { 4062 return new IndirectBrInst(*this); 4063 } 4064 4065 InvokeInst *InvokeInst::cloneImpl() const { 4066 if (hasOperandBundles()) { 4067 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4068 return new(getNumOperands(), DescriptorBytes) InvokeInst(*this); 4069 } 4070 return new(getNumOperands()) InvokeInst(*this); 4071 } 4072 4073 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); } 4074 4075 CleanupEndPadInst *CleanupEndPadInst::cloneImpl() const { 4076 return new (getNumOperands()) CleanupEndPadInst(*this); 4077 } 4078 4079 CleanupReturnInst *CleanupReturnInst::cloneImpl() const { 4080 return new (getNumOperands()) CleanupReturnInst(*this); 4081 } 4082 4083 CatchEndPadInst *CatchEndPadInst::cloneImpl() const { 4084 return new (getNumOperands()) CatchEndPadInst(*this); 4085 } 4086 4087 CatchReturnInst *CatchReturnInst::cloneImpl() const { 4088 return new (getNumOperands()) CatchReturnInst(*this); 4089 } 4090 4091 CatchPadInst *CatchPadInst::cloneImpl() const { 4092 return new (getNumOperands()) CatchPadInst(*this); 4093 } 4094 4095 TerminatePadInst *TerminatePadInst::cloneImpl() const { 4096 return new (getNumOperands()) TerminatePadInst(*this); 4097 } 4098 4099 CleanupPadInst *CleanupPadInst::cloneImpl() const { 4100 return new (getNumOperands()) CleanupPadInst(*this); 4101 } 4102 4103 UnreachableInst *UnreachableInst::cloneImpl() const { 4104 LLVMContext &Context = getContext(); 4105 return new UnreachableInst(Context); 4106 } 4107