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