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