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