llvm.org GIT mirror llvm / 0a5372e
Begin the painful process of tearing apart the rat'ss nest that is Constants.cpp and ConstantFold.cpp. This involves temporarily hard wiring some parts to use the global context. This isn't ideal, but it's the only way I could figure out to make this process vaguely incremental. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@75445 91177308-0d34-0410-b5e6-96231b3b80d8 Owen Anderson 10 years ago
43 changed file(s) with 556 addition(s) and 489 deletion(s). Raw diff Collapse all Expand all
855855 NamedValues.erase(VarName);
856856
857857 // for expr always returns 0.0.
858 return Constant::getNullValue(Type::DoubleTy);
858 return TheFunction->getContext()->getNullValue(Type::DoubleTy);
859859 }
860860
861861
15691569
15701570
15711571 // for expr always returns 0.0.
1572 return Constant::getNullValue(Type::DoubleTy);
1572 return TheFunction->getContext()->getNullValue(Type::DoubleTy);
15731573 }
15741574
15751575 Function *PrototypeAST::Codegen() {
18571857
18581858
18591859 // for expr always returns 0.0.
1860 return Constant::getNullValue(Type::DoubleTy);
1860 return TheFunction->getContext()->getNullValue(Type::DoubleTy);
18611861 }
18621862
18631863 Value *VarExprAST::Codegen() {
144144
145145 //call i32 @puts(i8 *getelementptr([%d x i8] *@aberrormsg, i32 0, i32 0))
146146 {
147 Constant *zero_32 = Constant::getNullValue(IntegerType::Int32Ty);
147 Constant *zero_32 = C.getNullValue(IntegerType::Int32Ty);
148148
149149 Constant *gep_params[] = {
150150 zero_32,
853853
854854
855855 // for expr always returns 0.0.
856 return Constant::getNullValue(Type::DoubleTy);
856 return TheFunction->getContext()->getNullValue(Type::DoubleTy);
857857 }
858858
859859 Value *VarExprAST::Codegen() {
5959 const TargetData &TD;
6060 const TargetInstrInfo &TII;
6161 const TargetLowering &TLI;
62 LLVMContext *Context;
6263
6364 public:
6465 /// startNewBlock - Set the current block to which generated machine
1717
1818 namespace llvm {
1919 template class SmallVectorImpl;
20 class LLVMContext;
2021
2122 /// If object contains references to other objects, then relocations are
2223 /// usually required for emission of such object (especially in PIC mode). One
5859
5960 void destroyConstantImpl();
6061 public:
61 /// Static constructor to get a '0' constant of arbitrary type...
62 ///
63 static Constant *getNullValue(const Type *Ty);
64
6562 /// Static constructor to get a '-1' constant. This supports integers and
6663 /// vectors.
6764 ///
9794 /// type, returns the elements of the vector in the specified smallvector.
9895 /// This handles breaking down a vector undef into undef elements, etc. For
9996 /// constant exprs and other cases we can't handle, we return an empty vector.
100 void getVectorElements(SmallVectorImpl &Elts) const;
97 void getVectorElements(LLVMContext &Context,
98 SmallVectorImpl &Elts) const;
10199
102100 /// destroyConstant - Called if some element of this constant is no longer
103101 /// valid. At this point only other constants may be on the use_list for this
275275 /// considers -0.0 to be null as well as 0.0. :(
276276 virtual bool isNullValue() const;
277277
278 // Get a negative zero.
279 static ConstantFP *getNegativeZero(const Type* Ty);
280
281278 /// isExactlyValue - We don't rely on operator== working on double values, as
282279 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
283280 /// As such, this method can be used to do an exact bit-for-bit comparison of
382379 /// isString) and it ends in a null byte \0 and does not contains any other
383380 /// @endverbatim
384381 /// null bytes except its terminator.
385 bool isCString() const;
382 bool isCString(LLVMContext &Context) const;
386383
387384 /// getAsString - If this array is isString(), then this method converts the
388385 /// array to an std::string and returns it. Otherwise, it asserts out.
693690 return getSelectTy(V1->getType(), C, V1, V2);
694691 }
695692
696 /// getAlignOf constant expr - computes the alignment of a type in a target
697 /// independent way (Note: the return type is an i32; Note: assumes that i8
698 /// is byte aligned).
699 ///
700 static Constant *getAlignOf(const Type *Ty);
701
702 /// getSizeOf constant expr - computes the size of a type in a target
703 /// independent way (Note: the return type is an i64).
704 ///
705 static Constant *getSizeOf(const Type *Ty);
706
707693 /// ConstantExpr::get - Return a binary or shift operator constant expression,
708694 /// folding if possible.
709695 ///
715701 /// ConstantExpr::get* - Return some common constants without having to
716702 /// specify the full Instruction::OPCODE identifier.
717703 ///
718 static Constant *getNeg(Constant *C);
719 static Constant *getFNeg(Constant *C);
720704 static Constant *getNot(Constant *C);
721705 static Constant *getAdd(Constant *C1, Constant *C2);
722706 static Constant *getFAdd(Constant *C1, Constant *C2);
755739 static Constant *getInsertValue(Constant *Agg, Constant *Val,
756740 const unsigned *IdxList, unsigned NumIdx);
757741
758 /// Floating point negation must be implemented with f(x) = -0.0 - x. This
759 /// method returns the negative zero constant for floating point or vector
760 /// floating point types; for all other types, it returns the null value.
761 static Constant *getZeroValueForNegationExpr(const Type *Ty);
762
763742 /// isNullValue - Return true if this is the value that would be returned by
764743 /// getNullValue.
765744 virtual bool isNullValue() const { return false; }
201201 /// CreateNeg, CreateNot - Create the NEG and NOT
202202 /// instructions out of SUB and XOR instructions.
203203 ///
204 static BinaryOperator *CreateNeg(Value *Op, const std::string &Name = "",
204 static BinaryOperator *CreateNeg(LLVMContext &Context,
205 Value *Op, const std::string &Name = "",
205206 Instruction *InsertBefore = 0);
206 static BinaryOperator *CreateNeg(Value *Op, const std::string &Name,
207 static BinaryOperator *CreateNeg(LLVMContext &Context,
208 Value *Op, const std::string &Name,
207209 BasicBlock *InsertAtEnd);
208 static BinaryOperator *CreateFNeg(Value *Op, const std::string &Name = "",
210 static BinaryOperator *CreateFNeg(LLVMContext &Context,
211 Value *Op, const std::string &Name = "",
209212 Instruction *InsertBefore = 0);
210 static BinaryOperator *CreateFNeg(Value *Op, const std::string &Name,
213 static BinaryOperator *CreateFNeg(LLVMContext &Context,
214 Value *Op, const std::string &Name,
211215 BasicBlock *InsertAtEnd);
212216 static BinaryOperator *CreateNot(Value *Op, const std::string &Name = "",
213217 Instruction *InsertBefore = 0);
217221 /// isNeg, isFNeg, isNot - Check if the given Value is a
218222 /// NEG, FNeg, or NOT instruction.
219223 ///
220 static bool isNeg(const Value *V);
221 static bool isFNeg(const Value *V);
224 static bool isNeg(LLVMContext &Context, const Value *V);
225 static bool isFNeg(LLVMContext &Context, const Value *V);
222226 static bool isNot(const Value *V);
223227
224228 /// getNegArgument, getNotArgument - Helper functions to extract the
119119 bool isSigned);
120120 Constant* getConstantExprFPCast(Constant* C, const Type* Ty);
121121 Constant* getConstantExprSelect(Constant* C, Constant* V1, Constant* V2);
122
123 /// getAlignOf constant expr - computes the alignment of a type in a target
124 /// independent way (Note: the return type is an i32; Note: assumes that i8
125 /// is byte aligned).
126 ///
122127 Constant* getConstantExprAlignOf(const Type* Ty);
123128 Constant* getConstantExprCompare(unsigned short pred,
124129 Constant* C1, Constant* C2);
161166 Constant* getConstantExprInsertValue(Constant* Agg, Constant* Val,
162167 const unsigned* IdxList,
163168 unsigned NumIdx);
169
170 /// getSizeOf constant expr - computes the size of a type in a target
171 /// independent way (Note: the return type is an i64).
172 ///
164173 Constant* getConstantExprSizeOf(const Type* Ty);
174
175 /// Floating point negation must be implemented with f(x) = -0.0 - x. This
176 /// method returns the negative zero constant for floating point or vector
177 /// floating point types; for all other types, it returns the null value.
165178 Constant* getZeroValueForNegation(const Type* Ty);
166179
167180 // ConstantFP accessors
199212 StructType* getStructType(bool isPacked=false);
200213 StructType* getStructType(const std::vector& Params,
201214 bool isPacked = false);
215 StructType* getStructType(const Type* type, ...);
202216
203217 // ArrayType accessors
204218 ArrayType* getArrayType(const Type* ElementType, uint64_t NumElements);
310310 Value *CreateNeg(Value *V, const char *Name = "") {
311311 if (Constant *VC = dyn_cast(V))
312312 return Folder.CreateNeg(VC);
313 return Insert(BinaryOperator::CreateNeg(V), Name);
313 return Insert(BinaryOperator::CreateNeg(getGlobalContext(), V), Name);
314314 }
315315 Value *CreateFNeg(Value *V, const char *Name = "") {
316316 if (Constant *VC = dyn_cast(V))
317317 return Folder.CreateFNeg(VC);
318 return Insert(BinaryOperator::CreateFNeg(V), Name);
318 return Insert(BinaryOperator::CreateFNeg(getGlobalContext(), V), Name);
319319 }
320320 Value *CreateNot(Value *V, const char *Name = "") {
321321 if (Constant *VC = dyn_cast(V))
462462 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
463463 /// This is only valid when the descriptor is non-null.
464464 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
465 if (D.isNull()) return Constant::getNullValue(EmptyStructPtr);
465 if (D.isNull()) return VMContext.getNullValue(EmptyStructPtr);
466466 return VMContext.getConstantExprBitCast(D.getGV(), EmptyStructPtr);
467467 }
468468
692692 // If the object in the points-to set is the null object, then the null
693693 // pointer is a must alias.
694694 if (Pointee == &GraphNodes[NullObject])
695 RetVals.push_back(Constant::getNullValue(P->getType()));
695 RetVals.push_back(Context->getNullValue(P->getType()));
696696 }
697697 }
698698 AliasAnalysis::getMustAliases(P, RetVals);
20832083 ///
20842084 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
20852085 if (const SCEVConstant *VC = dyn_cast(V))
2086 return getConstant(cast(ConstantExpr::getNeg(VC->getValue())));
2086 return getConstant(
2087 cast(Context->getConstantExprNeg(VC->getValue())));
20872088
20882089 const Type *Ty = V->getType();
20892090 Ty = getEffectiveSCEVType(Ty);
32833284 /// the addressed element of the initializer or null if the index expression is
32843285 /// invalid.
32853286 static Constant *
3286 GetAddressedElementFromGlobal(GlobalVariable *GV,
3287 GetAddressedElementFromGlobal(LLVMContext *Context, GlobalVariable *GV,
32873288 const std::vector &Indices) {
32883289 Constant *Init = GV->getInitializer();
32893290 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
32973298 } else if (isa(Init)) {
32983299 if (const StructType *STy = dyn_cast(Init->getType())) {
32993300 assert(Idx < STy->getNumElements() && "Bad struct index!");
3300 Init = Constant::getNullValue(STy->getElementType(Idx));
3301 Init = Context->getNullValue(STy->getElementType(Idx));
33013302 } else if (const ArrayType *ATy = dyn_cast(Init->getType())) {
33023303 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3303 Init = Constant::getNullValue(ATy->getElementType());
3304 Init = Context->getNullValue(ATy->getElementType());
33043305 } else {
33053306 LLVM_UNREACHABLE("Unknown constant aggregate type!");
33063307 }
33713372 // Form the GEP offset.
33723373 Indexes[VarIdxNum] = Val;
33733374
3374 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3375 Constant *Result = GetAddressedElementFromGlobal(Context, GV, Indexes);
33753376 if (Result == 0) break; // Cannot compute!
33763377
33773378 // Evaluate the condition for this iteration.
314314
315315 void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
316316 IRBuilder<> Builder(CI->getParent(), CI);
317 LLVMContext *Context = CI->getParent()->getContext();
317318
318319 Function *Callee = CI->getCalledFunction();
319320 assert(Callee && "Cannot lower an indirect call!");
339340 }
340341 case Intrinsic::sigsetjmp:
341342 if (CI->getType() != Type::VoidTy)
342 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
343 CI->replaceAllUsesWith(Context->getNullValue(CI->getType()));
343344 break;
344345
345346 case Intrinsic::longjmp: {
386387 "save" : "restore") << " intrinsic.\n";
387388 Warned = true;
388389 if (Callee->getIntrinsicID() == Intrinsic::stacksave)
389 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
390 CI->replaceAllUsesWith(Context->getNullValue(CI->getType()));
390391 break;
391392 }
392393
421422 case Intrinsic::eh_exception:
422423 case Intrinsic::eh_selector_i32:
423424 case Intrinsic::eh_selector_i64:
424 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
425 CI->replaceAllUsesWith(Context->getNullValue(CI->getType()));
425426 break;
426427
427428 case Intrinsic::eh_typeid_for_i32:
122122 // getConstSection - Get constant section for Constant 'C'
123123 MachOSection *MachOWriter::getConstSection(Constant *C) {
124124 const ConstantArray *CVA = dyn_cast(C);
125 if (CVA && CVA->isCString())
125 if (CVA && CVA->isCString(*Context))
126126 return getSection("__TEXT", "__cstring",
127127 MachOSection::S_CSTRING_LITERALS);
128128
9191 } else if (isa(V)) {
9292 // Translate this as an integer zero so that it can be
9393 // local-CSE'd with actual integer zeros.
94 Reg = getRegForValue(Constant::getNullValue(TD.getIntPtrType()));
94 Reg = getRegForValue(Context->getNullValue(TD.getIntPtrType()));
9595 } else if (ConstantFP *CF = dyn_cast(V)) {
9696 Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
9797
479479 UpdateValueMap(I, ResultReg);
480480 } else {
481481 unsigned ResultReg =
482 getRegForValue(Constant::getNullValue(I->getType()));
482 getRegForValue(Context->getNullValue(I->getType()));
483483 UpdateValueMap(I, ResultReg);
484484 }
485485 return true;
752752 TM(MF.getTarget()),
753753 TD(*TM.getTargetData()),
754754 TII(*TM.getInstrInfo()),
755 TLI(*TM.getTargetLowering()) {
755 TLI(*TM.getTargetLowering()),
756 Context(mf.getFunction()->getContext()) {
756757 }
757758
758759 FastISel::~FastISel() {}
21382138 const VectorType *DestTy = cast(I.getType());
21392139 const Type *ElTy = DestTy->getElementType();
21402140 unsigned VL = DestTy->getNumElements();
2141 std::vector NZ(VL, ConstantFP::getNegativeZero(ElTy));
2141 std::vector NZ(VL, Context->getConstantFPNegativeZero(ElTy));
21422142 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
21432143 if (CV == CNZ) {
21442144 SDValue Op2 = getValue(I.getOperand(1));
21492149 }
21502150 }
21512151 if (ConstantFP *CFP = dyn_cast(I.getOperand(0)))
2152 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2152 if (CFP->isExactlyValue(
2153 Context->getConstantFPNegativeZero(Ty)->getValueAPF())) {
21532154 SDValue Op2 = getValue(I.getOperand(1));
21542155 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
21552156 Op2.getValueType(), Op2));
23972398 // Convert the ConstantVector mask operand into an array of ints, with -1
23982399 // representing undef values.
23992400 SmallVector MaskElts;
2400 cast(I.getOperand(2))->getVectorElements(MaskElts);
2401 cast(I.getOperand(2))->getVectorElements(*Context, MaskElts);
24012402 unsigned MaskNumElts = MaskElts.size();
24022403 for (unsigned i = 0; i != MaskNumElts; ++i) {
24032404 if (isa(MaskElts[i]))
1414 #define SELECTIONDAGBUILD_H
1515
1616 #include "llvm/Constants.h"
17 #include "llvm/CodeGen/SelectionDAG.h"
1718 #include "llvm/ADT/APInt.h"
1819 #include "llvm/ADT/DenseMap.h"
1920 #ifndef NDEBUG
361362 /// GFI - Garbage collection metadata for the function.
362363 GCFunctionInfo *GFI;
363364
365 LLVMContext *Context;
366
364367 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
365368 FunctionLoweringInfo &funcinfo,
366369 CodeGenOpt::Level ol)
367370 : CurDebugLoc(DebugLoc::getUnknownLoc()),
368 TLI(tli), DAG(dag), FuncInfo(funcinfo), OptLevel(ol) {
371 TLI(tli), DAG(dag), FuncInfo(funcinfo), OptLevel(ol),
372 Context(dag.getContext()) {
369373 }
370374
371375 void init(GCFunctionInfo *gfi, AliasAnalysis &aa);
292292 // linkage!
293293 Head = new GlobalVariable(M, StackEntryPtrTy, false,
294294 GlobalValue::LinkOnceAnyLinkage,
295 Constant::getNullValue(StackEntryPtrTy),
295 M.getContext().getNullValue(StackEntryPtrTy),
296296 "llvm_gc_root_chain");
297297 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
298 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
298 Head->setInitializer(M.getContext().getNullValue(StackEntryPtrTy));
299299 Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
300300 }
301301
6767 BasicBlock *BB = I;
6868 DeadBlocks.push_back(BB);
6969 while (PHINode *PN = dyn_cast(BB->begin())) {
70 PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
70 PN->replaceAllUsesWith(Context->getNullValue(PN->getType()));
7171 BB->getInstList().pop_front();
7272 }
7373 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12381238 Out << '{';
12391239 if (AT->getNumElements()) {
12401240 Out << ' ';
1241 Constant *CZ = Constant::getNullValue(AT->getElementType());
1241 Constant *CZ = Context->getNullValue(AT->getElementType());
12421242 printConstant(CZ, Static);
12431243 for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
12441244 Out << ", ";
12631263 assert(isa(CPV) || isa(CPV));
12641264 const VectorType *VT = cast(CPV->getType());
12651265 Out << "{ ";
1266 Constant *CZ = Constant::getNullValue(VT->getElementType());
1266 Constant *CZ = Context->getNullValue(VT->getElementType());
12671267 printConstant(CZ, Static);
12681268 for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
12691269 Out << ", ";
12851285 Out << '{';
12861286 if (ST->getNumElements()) {
12871287 Out << ' ';
1288 printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
1288 printConstant(Context->getNullValue(ST->getElementType(0)), Static);
12891289 for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
12901290 Out << ", ";
1291 printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
1291 printConstant(Context->getNullValue(ST->getElementType(i)), Static);
12921292 }
12931293 }
12941294 Out << " }";
26202620
26212621 // If this is a negation operation, print it out as such. For FP, we don't
26222622 // want to print "-0.0 - X".
2623 if (BinaryOperator::isNeg(&I)) {
2623 if (BinaryOperator::isNeg(*Context, &I)) {
26242624 Out << "-(";
26252625 writeOperand(BinaryOperator::getNegArgument(cast(&I)));
26262626 Out << ")";
2627 } else if (BinaryOperator::isFNeg(&I)) {
2627 } else if (BinaryOperator::isFNeg(*Context, &I)) {
26282628 Out << "-(";
26292629 writeOperand(BinaryOperator::getFNegArgument(cast(&I)));
26302630 Out << ")";
540540 // Fall Through
541541 case GlobalValue::PrivateLinkage:
542542 case GlobalValue::InternalLinkage:
543 if (CVA && CVA->isCString())
543 if (CVA && CVA->isCString(GVar->getParent()->getContext()))
544544 printSizeAndType = false;
545545 break;
546546 case GlobalValue::GhostLinkage:
226226 if (GVA->hasInitializer() && GV->hasLocalLinkage()) {
227227 Constant *C = GVA->getInitializer();
228228 const ConstantArray *CVA = dyn_cast(C);
229 if (CVA && CVA->isCString())
229 if (CVA && CVA->isCString(GV->getParent()->getContext()))
230230 return false;
231231 }
232232
169169 return (C->isNullValue() && !GV->isConstant() && !NoZerosInBSS);
170170 }
171171
172 static bool isConstantString(const Constant *C) {
172 static bool isConstantString(LLVMContext &Context, const Constant *C) {
173173 // First check: is we have constant array of i8 terminated with zero
174174 const ConstantArray *CVA = dyn_cast(C);
175175 // Check, if initializer is a null-terminated string
176 if (CVA && CVA->isCString())
176 if (CVA && CVA->isCString(Context))
177177 return true;
178178
179179 // Another possibility: [1 x i8] zeroinitializer
228228 }
229229 } else {
230230 // Check, if initializer is a null-terminated string
231 if (isConstantString(C))
231 if (isConstantString(GV->getParent()->getContext(), C))
232232 return SectionKind::RODataMergeStr;
233233 else
234234 return SectionKind::RODataMergeConst;
271271 const X86AddressMode &AM) {
272272 // Handle 'null' like i32/i64 0.
273273 if (isa(Val))
274 Val = Constant::getNullValue(TD.getIntPtrType());
274 Val = Context->getNullValue(TD.getIntPtrType());
275275
276276 // If this is a store of a simple constant, fold the constant into the store.
277277 if (ConstantInt *CI = dyn_cast(Val)) {
671671
672672 // Handle 'null' like i32/i64 0.
673673 if (isa(Op1))
674 Op1 = Constant::getNullValue(TD.getIntPtrType());
674 Op1 = Context->getNullValue(TD.getIntPtrType());
675675
676676 // We have two options: compare with register or immediate. If the RHS of
677677 // the compare is an immediate that we can fold into this compare, use
1919 #include "X86TargetMachine.h"
2020 #include "llvm/GlobalVariable.h"
2121 #include "llvm/DerivedTypes.h"
22 #include "llvm/LLVMContext.h"
2223 #include "llvm/ADT/STLExtras.h"
2324 #include "llvm/CodeGen/MachineConstantPool.h"
2425 #include "llvm/CodeGen/MachineFrameInfo.h"
23112312 MachineConstantPool &MCP = *MF.getConstantPool();
23122313 const VectorType *Ty = VectorType::get(Type::Int32Ty, 4);
23132314 Constant *C = LoadMI->getOpcode() == X86::V_SET0 ?
2314 ConstantVector::getNullValue(Ty) :
2315 MF.getFunction()->getContext()->getNullValue(Ty) :
23152316 ConstantVector::getAllOnesValue(Ty);
23162317 unsigned CPI = MCP.getConstantPoolIndex(C, 16);
23172318
407407
408408 // getComplexity: Assign a complexity or rank value to LLVM Values...
409409 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
410 static unsigned getComplexity(Value *V) {
410 static unsigned getComplexity(LLVMContext *Context, Value *V) {
411411 if (isa(V)) {
412 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
412 if (BinaryOperator::isNeg(*Context, V) ||
413 BinaryOperator::isFNeg(*Context, V) ||
413414 BinaryOperator::isNot(V))
414415 return 3;
415416 return 4;
520521 //
521522 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
522523 bool Changed = false;
523 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
524 if (getComplexity(Context, I.getOperand(0)) <
525 getComplexity(Context, I.getOperand(1)))
524526 Changed = !I.swapOperands();
525527
526528 if (!I.isAssociative()) return Changed;
558560 /// so that theyare listed from right (least complex) to left (most complex).
559561 /// This puts constants before unary operators before binary operators.
560562 bool InstCombiner::SimplifyCompare(CmpInst &I) {
561 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
563 if (getComplexity(Context, I.getOperand(0)) >=
564 getComplexity(Context, I.getOperand(1)))
562565 return false;
563566 I.swapOperands();
564567 // Compare instructions are not associative so there's nothing else we can do.
569572 // if the LHS is a constant zero (which is the 'negate' form).
570573 //
571574 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
572 if (BinaryOperator::isNeg(V))
575 if (BinaryOperator::isNeg(*Context, V))
573576 return BinaryOperator::getNegArgument(V);
574577
575578 // Constants can be considered to be negated values if they can be folded.
588591 // form).
589592 //
590593 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
591 if (BinaryOperator::isFNeg(V))
594 if (BinaryOperator::isFNeg(*Context, V))
592595 return BinaryOperator::getFNegArgument(V);
593596
594597 // Constants can be considered to be negated values if they can be folded.
21842187 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
21852188 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
21862189 InsertNewInstBefore(NewAdd, I);
2187 return BinaryOperator::CreateNeg(NewAdd);
2190 return BinaryOperator::CreateNeg(*Context, NewAdd);
21882191 }
21892192 }
21902193
25292532 if (BinaryOperator *Op1I = dyn_cast(Op1)) {
25302533 if (Op1I->getOpcode() == Instruction::Add) {
25312534 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2532 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2535 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2536 I.getName());
25332537 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2534 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2538 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2539 I.getName());
25352540 else if (ConstantInt *CI1 = dyn_cast(I.getOperand(0))) {
25362541 if (ConstantInt *CI2 = dyn_cast(Op1I->getOperand(1)))
25372542 // C1-(X+C2) --> (C1-C2)-X
25922597 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
25932598 } else if (Op0I->getOpcode() == Instruction::Sub) {
25942599 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2595 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2600 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2601 I.getName());
25962602 }
25972603 }
25982604
26182624 if (BinaryOperator *Op1I = dyn_cast(Op1)) {
26192625 if (Op1I->getOpcode() == Instruction::FAdd) {
26202626 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2621 return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2627 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2628 I.getName());
26222629 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2623 return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2630 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2631 I.getName());
26242632 }
26252633 }
26262634
26822690 if (CI->equalsInt(1)) // X * 1 == X
26832691 return ReplaceInstUsesWith(I, Op0);
26842692 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2685 return BinaryOperator::CreateNeg(Op0, I.getName());
2693 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
26862694
26872695 const APInt& Val = cast(CI)->getValue();
26882696 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
26942702
26952703 if (ConstantVector *Op1V = dyn_cast(Op1)) {
26962704 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2697 return BinaryOperator::CreateNeg(Op0, I.getName());
2705 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
26982706
26992707 // As above, vector X*splat(1.0) -> X in all defined cases.
27002708 if (Constant *Splat = Op1V->getSplatValue()) {
31073115 if (ConstantInt *RHS = dyn_cast(Op1)) {
31083116 // sdiv X, -1 == -X
31093117 if (RHS->isAllOnesValue())
3110 return BinaryOperator::CreateNeg(Op0);
3118 return BinaryOperator::CreateNeg(*Context, Op0);
31113119 }
31123120
31133121 // If the sign bits of both operands are zero (i.e. we can prove they are
40414049 ConstantInt *A = dyn_cast(Op0LHS);
40424050 if (!(A && A->isZero()) && // avoid infinite recursion.
40434051 MaskedValueIsZero(Op0LHS, Mask)) {
4044 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4052 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
40454053 InsertNewInstBefore(NewNeg, I);
40464054 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
40474055 }
70937101 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
70947102 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
70957103 else if (BO->hasOneUse()) {
7096 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7104 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
70977105 InsertNewInstBefore(Neg, ICI);
70987106 Neg->takeName(BO);
70997107 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
95869594 NegVal = Context->getConstantExprNeg(C);
95879595 } else {
95889596 NegVal = InsertNewInstBefore(
9589 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9597 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9598 "tmp"), SI);
95909599 }
95919600
95929601 Value *NewTrueOp = OtherAddOp;
13401340 BasicBlock *TopBB;
13411341 Instruction *TopInst;
13421342 bool &modified;
1343 LLVMContext *Context;
13431344
13441345 typedef InequalityGraph::Node Node;
13451346
16591660 Top(DTDFS->getNodeForBlock(TopBB)),
16601661 TopBB(TopBB),
16611662 TopInst(NULL),
1662 modified(modified)
1663 modified(modified),
1664 Context(TopBB->getContext())
16631665 {
16641666 assert(Top && "VRPSolver created for unreachable basic block.");
16651667 }
17591761 } break;
17601762 case Instruction::Or: {
17611763 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
1762 Constant *Zero = Constant::getNullValue(Ty);
1764 Constant *Zero = Context->getNullValue(Ty);
17631765 if (Canonical == Zero) {
17641766 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
17651767 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
17821784 }
17831785 if (Canonical == LHS) {
17841786 if (isa(Canonical))
1785 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1787 add(RHS, Context->getNullValue(Ty), ICmpInst::ICMP_EQ,
17861788 NewContext);
17871789 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1788 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1790 add(RHS, Context->getNullValue(Ty), ICmpInst::ICMP_NE,
17891791 NewContext);
17901792 }
17911793 } break;
18301832 }
18311833 // TODO: The GEPI indices are all zero. Copy from definition to operand,
18321834 // jumping the type plane as needed.
1833 if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
1835 if (isRelatedBy(GEPI, Context->getNullValue(GEPI->getType()),
18341836 ICmpInst::ICMP_NE)) {
18351837 Value *Ptr = GEPI->getPointerOperand();
1836 add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1838 add(Ptr, Context->getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
18371839 NewContext);
18381840 }
18391841 } else if (CastInst *CI = dyn_cast(I)) {
18871889 const Type *Ty = BO->getType();
18881890 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
18891891
1890 Constant *Zero = Constant::getNullValue(Ty);
1892 Constant *Zero = Context->getNullValue(Ty);
18911893 Constant *One = ConstantInt::get(Ty, 1);
18921894 ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
18931895
21092111 // TODO: The GEPI indices are all zero. Copy from operand to definition,
21102112 // jumping the type plane as needed.
21112113 Value *Ptr = GEPI->getPointerOperand();
2112 if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
2114 if (isRelatedBy(Ptr, Context->getNullValue(Ptr->getType()),
21132115 ICmpInst::ICMP_NE)) {
2114 add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
2116 add(GEPI, Context->getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
21152117 NewContext);
21162118 }
21172119 }
24952497
24962498 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
24972499 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
2498 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
2500 VRP.add(AI.getParent()->getContext()->getNullValue(AI.getType()),
2501 &AI, ICmpInst::ICMP_NE);
24992502 VRP.solve();
25002503 }
25012504
25052508 if (isa(Ptr)) return;
25062509
25072510 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
2508 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
2511 VRP.add(LI.getParent()->getContext()->getNullValue(Ptr->getType()),
2512 Ptr, ICmpInst::ICMP_NE);
25092513 VRP.solve();
25102514 }
25112515
25142518 if (isa(Ptr)) return;
25152519
25162520 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2517 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
2521 VRP.add(SI.getParent()->getContext()->getNullValue(Ptr->getType()),
2522 Ptr, ICmpInst::ICMP_NE);
25182523 VRP.solve();
25192524 }
25202525
25492554 case Instruction::SDiv: {
25502555 Value *Divisor = BO.getOperand(1);
25512556 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2552 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
2553 ICmpInst::ICMP_NE);
2557 VRP.add(BO.getParent()->getContext()->getNullValue(Divisor->getType()),
2558 Divisor, ICmpInst::ICMP_NE);
25542559 VRP.solve();
25552560 break;
25562561 }
177177 // If this is a not or neg instruction, do not count it for rank. This
178178 // assures us that X and ~X will have the same rank.
179179 if (!I->getType()->isInteger() ||
180 (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
180 (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(*Context, I)))
181181 ++Rank;
182182
183183 //DOUT << "Calculated Rank[" << V->getName() << "] = "
263263 // If this is a multiply expression tree and it contains internal negations,
264264 // transform them into multiplies by -1 so they can be reassociated.
265265 if (I->getOpcode() == Instruction::Mul) {
266 if (!LHSBO && LHS->hasOneUse() && BinaryOperator::isNeg(LHS)) {
266 if (!LHSBO && LHS->hasOneUse() && BinaryOperator::isNeg(*Context, LHS)) {
267267 LHS = LowerNegateToMultiply(cast(LHS),
268268 ValueRankMap, Context);
269269 LHSBO = isReassociableOp(LHS, Opcode);
270270 }
271 if (!RHSBO && RHS->hasOneUse() && BinaryOperator::isNeg(RHS)) {
271 if (!RHSBO && RHS->hasOneUse() && BinaryOperator::isNeg(*Context, RHS)) {
272272 RHS = LowerNegateToMultiply(cast(RHS),
273273 ValueRankMap, Context);
274274 RHSBO = isReassociableOp(RHS, Opcode);
372372 // version of the value is returned, and BI is left pointing at the instruction
373373 // that should be processed next by the reassociation pass.
374374 //
375 static Value *NegateValue(Value *V, Instruction *BI) {
375 static Value *NegateValue(LLVMContext *Context, Value *V, Instruction *BI) {
376376 // We are trying to expose opportunity for reassociation. One of the things
377377 // that we want to do to achieve this is to push a negation as deep into an
378378 // expression chain as possible, to expose the add instructions. In practice,
385385 if (Instruction *I = dyn_cast(V))
386386 if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
387387 // Push the negates through the add.
388 I->setOperand(0, NegateValue(I->getOperand(0), BI));
389 I->setOperand(1, NegateValue(I->getOperand(1), BI));
388 I->setOperand(0, NegateValue(Context, I->getOperand(0), BI));
389 I->setOperand(1, NegateValue(Context, I->getOperand(1), BI));
390390
391391 // We must move the add instruction here, because the neg instructions do
392392 // not dominate the old add instruction in general. By moving it, we are
401401 // Insert a 'neg' instruction that subtracts the value from zero to get the
402402 // negation.
403403 //
404 return BinaryOperator::CreateNeg(V, V->getName() + ".neg", BI);
404 return BinaryOperator::CreateNeg(*Context, V, V->getName() + ".neg", BI);
405405 }
406406
407407 /// ShouldBreakUpSubtract - Return true if we should break up this subtract of
408408 /// X-Y into (X + -Y).
409 static bool ShouldBreakUpSubtract(Instruction *Sub) {
409 static bool ShouldBreakUpSubtract(LLVMContext *Context, Instruction *Sub) {
410410 // If this is a negation, we can't split it up!
411 if (BinaryOperator::isNeg(Sub))
411 if (BinaryOperator::isNeg(*Context, Sub))
412412 return false;
413413
414414 // Don't bother to break this up unless either the LHS is an associable add or
430430 /// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
431431 /// only used by an add, transform this into (X+(0-Y)) to promote better
432432 /// reassociation.
433 static Instruction *BreakUpSubtract(Instruction *Sub,
433 static Instruction *BreakUpSubtract(LLVMContext *Context, Instruction *Sub,
434434 std::map, unsigned> &ValueRankMap) {
435435 // Convert a subtract into an add and a neg instruction... so that sub
436436 // instructions can be commuted with other add instructions...
438438 // Calculate the negative value of Operand 1 of the sub instruction...
439439 // and set it as the RHS of the add instruction we just made...
440440 //
441 Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
441 Value *NegVal = NegateValue(Context, Sub->getOperand(1), Sub);
442442 Instruction *New =
443443 BinaryOperator::CreateAdd(Sub->getOperand(0), NegVal, "", Sub);
444444 New->takeName(Sub);
662662 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
663663 assert(i < Ops.size());
664664 // Check for X and -X in the operand list.
665 if (BinaryOperator::isNeg(Ops[i].Op)) {
665 if (BinaryOperator::isNeg(*Context, Ops[i].Op)) {
666666 Value *X = BinaryOperator::getNegArgument(Ops[i].Op);
667667 unsigned FoundX = FindInOperandList(Ops, i, X);
668668 if (FoundX != i) {
797797 // If this is a subtract instruction which is not already in negate form,
798798 // see if we can convert it to X+-Y.
799799 if (BI->getOpcode() == Instruction::Sub) {
800 if (ShouldBreakUpSubtract(BI)) {
801 BI = BreakUpSubtract(BI, ValueRankMap);
800 if (ShouldBreakUpSubtract(Context, BI)) {
801 BI = BreakUpSubtract(Context, BI, ValueRankMap);
802802 MadeChange = true;
803 } else if (BinaryOperator::isNeg(BI)) {
803 } else if (BinaryOperator::isNeg(*Context, BI)) {
804804 // Otherwise, this is a negation. See if the operand is a multiply tree
805805 // and if this is not an inner node of a multiply tree.
806806 if (isReassociableOp(BI->getOperand(1), Instruction::Mul) &&
250250 // Insert a return instruction. This really should be a "barrier", as it
251251 // is unreachable.
252252 ReturnInst::Create(F.getReturnType() == Type::VoidTy ? 0 :
253 Constant::getNullValue(F.getReturnType()), UI);
253 Context->getNullValue(F.getReturnType()), UI);
254254
255255 // Remove the unwind instruction now.
256256 BB->getInstList().erase(UI);
284284
285285 BasicBlock::iterator NI = II->getNormalDest()->getFirstNonPHI();
286286 // nonvolatile.
287 new StoreInst(Constant::getNullValue(Type::Int32Ty), InvokeNum, false, NI);
287 new StoreInst(Context->getNullValue(Type::Int32Ty), InvokeNum, false, NI);
288288
289289 // Add a switch case to our unwind block.
290290 CatchSwitch->addCase(InvokeNoC, II->getUnwindDest());
472472 new AllocaInst(JBLinkTy, 0, Align, "jblink", F.begin()->begin());
473473
474474 std::vector Idx;
475 Idx.push_back(Constant::getNullValue(Type::Int32Ty));
475 Idx.push_back(Context->getNullValue(Type::Int32Ty));
476476 Idx.push_back(ConstantInt::get(Type::Int32Ty, 1));
477477 OldJmpBufPtr = GetElementPtrInst::Create(JmpBuf, Idx.begin(), Idx.end(),
478478 "OldBuf", EntryBB->getTerminator());
524524 // Compare the return value to zero.
525525 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
526526 ICmpInst::ICMP_EQ, SJRet,
527 Constant::getNullValue(SJRet->getType()),
527 Context->getNullValue(SJRet->getType()),
528528 "notunwind");
529529 // Nuke the uncond branch.
530530 EntryBB->getTerminator()->eraseFromParent();
558558
559559 // Load the JBList, if it's null, then there was no catch!
560560 Value *NotNull = new ICmpInst(*UnwindHandler, ICmpInst::ICMP_NE, BufPtr,
561 Constant::getNullValue(BufPtr->getType()),
561 Context->getNullValue(BufPtr->getType()),
562562 "notnull");
563563 BranchInst::Create(UnwindBlock, TermBlock, NotNull, UnwindHandler);
564564
565565 // Create the block to do the longjmp.
566566 // Get a pointer to the jmpbuf and longjmp.
567567 std::vector Idx;
568 Idx.push_back(Constant::getNullValue(Type::Int32Ty));
568 Idx.push_back(Context->getNullValue(Type::Int32Ty));
569569 Idx.push_back(ConstantInt::get(Type::Int32Ty, 0));
570570 Idx[0] = GetElementPtrInst::Create(BufPtr, Idx.begin(), Idx.end(), "JmpBuf",
571571 UnwindBlock);
2323 #include "llvm/DerivedTypes.h"
2424 #include "llvm/Function.h"
2525 #include "llvm/GlobalAlias.h"
26 #include "llvm/LLVMContext.h"
2627 #include "llvm/ADT/SmallVector.h"
2728 #include "llvm/Support/Compiler.h"
2829 #include "llvm/Support/ErrorHandling.h"
3940 /// BitCastConstantVector - Convert the specified ConstantVector node to the
4041 /// specified vector type. At this point, we know that the elements of the
4142 /// input vector constant are all simple integer or FP values.
42 static Constant *BitCastConstantVector(ConstantVector *CV,
43 static Constant *BitCastConstantVector(LLVMContext &Context, ConstantVector *CV,
4344 const VectorType *DstTy) {
4445 // If this cast changes element count then we can't handle it here:
4546 // doing so requires endianness information. This should be handled by
5960 std::vector Result;
6061 const Type *DstEltTy = DstTy->getElementType();
6162 for (unsigned i = 0; i != NumElts; ++i)
62 Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i), DstEltTy));
63 return ConstantVector::get(Result);
63 Result.push_back(Context.getConstantExprBitCast(CV->getOperand(i),
64 DstEltTy));
65 return Context.getConstantVector(Result);
6466 }
6567
6668 /// This function determines which opcode to use to fold two constant cast
8890 Type::Int64Ty);
8991 }
9092
91 static Constant *FoldBitCast(Constant *V, const Type *DestTy) {
93 static Constant *FoldBitCast(LLVMContext &Context,
94 Constant *V, const Type *DestTy) {
9295 const Type *SrcTy = V->getType();
9396 if (SrcTy == DestTy)
9497 return V; // no-op cast
99102 if (const PointerType *DPTy = dyn_cast(DestTy))
100103 if (PTy->getAddressSpace() == DPTy->getAddressSpace()) {
101104 SmallVector IdxList;
102 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
105 IdxList.push_back(Context.getNullValue(Type::Int32Ty));
103106 const Type *ElTy = PTy->getElementType();
104107 while (ElTy != DPTy->getElementType()) {
105108 if (const StructType *STy = dyn_cast(ElTy)) {
106109 if (STy->getNumElements() == 0) break;
107110 ElTy = STy->getElementType(0);
108 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
111 IdxList.push_back(Context.getNullValue(Type::Int32Ty));
109112 } else if (const SequentialType *STy =
110113 dyn_cast(ElTy)) {
111114 if (isa(ElTy)) break; // Can't index into pointers!
117120 }
118121
119122 if (ElTy == DPTy->getElementType())
120 return ConstantExpr::getGetElementPtr(V, &IdxList[0], IdxList.size());
123 return Context.getConstantExprGetElementPtr(V, &IdxList[0],
124 IdxList.size());
121125 }
122126
123127 // Handle casts from one vector constant to another. We know that the src
129133 SrcTy = NULL;
130134 // First, check for null. Undef is already handled.
131135 if (isa(V))
132 return Constant::getNullValue(DestTy);
136 return Context.getNullValue(DestTy);
133137
134138 if (ConstantVector *CV = dyn_cast(V))
135 return BitCastConstantVector(CV, DestPTy);
139 return BitCastConstantVector(Context, CV, DestPTy);
136140 }
137141
138142 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
139143 // This allows for other simplifications (although some of them
140144 // can only be handled by Analysis/ConstantFolding.cpp).
141145 if (isa(V) || isa(V))
142 return ConstantExpr::getBitCast(ConstantVector::get(&V, 1), DestPTy);
146 return Context.getConstantExprBitCast(
147 Context.getConstantVector(&V, 1), DestPTy);
143148 }
144149
145150 // Finally, implement bitcast folding now. The code below doesn't handle
146151 // bitcast right.
147152 if (isa(V)) // ptr->ptr cast.
148 return ConstantPointerNull::get(cast(DestTy));
153 return Context.getConstantPointerNull(cast(DestTy));
149154
150155 // Handle integral constant input.
151156 if (const ConstantInt *CI = dyn_cast(V)) {
155160 return V;
156161
157162 if (DestTy->isFloatingPoint())
158 return ConstantFP::get(APFloat(CI->getValue(),
163 return Context.getConstantFP(APFloat(CI->getValue(),
159164 DestTy != Type::PPC_FP128Ty));
160165
161166 // Otherwise, can't fold this (vector?)
165170 // Handle ConstantFP input.
166171 if (const ConstantFP *FP = dyn_cast(V))
167172 // FP -> Integral.
168 return ConstantInt::get(FP->getValueAPF().bitcastToAPInt());
173 return Context.getConstantInt(FP->getValueAPF().bitcastToAPInt());
169174
170175 return 0;
171176 }
172177
173178
174 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
179 Constant *llvm::ConstantFoldCastInstruction(LLVMContext &Context,
180 unsigned opc, const Constant *V,
175181 const Type *DestTy) {
176182 if (isa(V)) {
177183 // zext(undef) = 0, because the top bits will be zero.
179185 // [us]itofp(undef) = 0, because the result value is bounded.
180186 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
181187 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
182 return Constant::getNullValue(DestTy);
183 return UndefValue::get(DestTy);
188 return Context.getNullValue(DestTy);
189 return Context.getUndef(DestTy);
184190 }
185191 // No compile-time operations on this type yet.
186192 if (V->getType() == Type::PPC_FP128Ty || DestTy == Type::PPC_FP128Ty)
192198 if (CE->isCast()) {
193199 // Try hard to fold cast of cast because they are often eliminable.
194200 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
195 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
201 return Context.getConstantExprCast(newOpc, CE->getOperand(0), DestTy);
196202 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
197203 // If all of the indexes in the GEP are null values, there is no pointer
198204 // adjustment going on. We might as well cast the source pointer.
204210 }
205211 if (isAllNull)
206212 // This is casting one pointer type to another, always BitCast
207 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
213 return Context.getConstantExprPointerCast(CE->getOperand(0), DestTy);
208214 }
209215 }
210216
219225 const VectorType *DestVecTy = cast(DestTy);
220226 const Type *DstEltTy = DestVecTy->getElementType();
221227 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
222 res.push_back(ConstantExpr::getCast(opc,
228 res.push_back(Context.getConstantExprCast(opc,
223229 CV->getOperand(i), DstEltTy));
224 return ConstantVector::get(DestVecTy, res);
230 return Context.getConstantVector(DestVecTy, res);
225231 }
226232
227233 // We actually have to do a cast now. Perform the cast according to the
238244 DestTy == Type::FP128Ty ? APFloat::IEEEquad :
239245 APFloat::Bogus,
240246 APFloat::rmNearestTiesToEven, &ignored);
241 return ConstantFP::get(Val);
247 return Context.getConstantFP(Val);
242248 }
243249 return 0; // Can't fold.
244250 case Instruction::FPToUI:
251257 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
252258 APFloat::rmTowardZero, &ignored);
253259 APInt Val(DestBitWidth, 2, x);
254 return ConstantInt::get(Val);
260 return Context.getConstantInt(Val);
255261 }
256262 return 0; // Can't fold.
257263 case Instruction::IntToPtr: //always treated as unsigned
258264 if (V->isNullValue()) // Is it an integral null value?
259 return ConstantPointerNull::get(cast(DestTy));
265 return Context.getConstantPointerNull(cast(DestTy));
260266 return 0; // Other pointer types cannot be casted
261267 case Instruction::PtrToInt: // always treated as unsigned
262268 if (V->isNullValue()) // is it a null pointer value?
263 return ConstantInt::get(DestTy, 0);
269 return Context.getConstantInt(DestTy, 0);
264270 return 0; // Other pointer types cannot be casted
265271 case Instruction::UIToFP:
266272 case Instruction::SIToFP:
272278 (void)apf.convertFromAPInt(api,
273279 opc==Instruction::SIToFP,
274280 APFloat::rmNearestTiesToEven);
275 return ConstantFP::get(apf);
281 return Context.getConstantFP(apf);
276282 }
277283 return 0;
278284 case Instruction::ZExt:
280286 uint32_t BitWidth = cast(DestTy)->getBitWidth();
281287 APInt Result(CI->getValue());
282288 Result.zext(BitWidth);
283 return ConstantInt::get(Result);
289 return Context.getConstantInt(Result);
284290 }
285291 return 0;
286292 case Instruction::SExt:
288294 uint32_t BitWidth = cast(DestTy)->getBitWidth();
289295 APInt Result(CI->getValue());
290296 Result.sext(BitWidth);
291 return ConstantInt::get(Result);
297 return Context.getConstantInt(Result);
292298 }
293299 return 0;
294300 case Instruction::Trunc:
296302 uint32_t BitWidth = cast(DestTy)->getBitWidth();
297303 APInt Result(CI->getValue());
298304 Result.trunc(BitWidth);
299 return ConstantInt::get(Result);
305 return Context.getConstantInt(Result);
300306 }
301307 return 0;
302308 case Instruction::BitCast:
303 return FoldBitCast(const_cast(V), DestTy);
309 return FoldBitCast(Context, const_cast(V), DestTy);
304310 default:
305311 assert(!"Invalid CE CastInst opcode");
306312 break;
310316 return 0;
311317 }
312318
313 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
319 Constant *llvm::ConstantFoldSelectInstruction(LLVMContext&,
320 const Constant *Cond,
314321 const Constant *V1,
315322 const Constant *V2) {
316323 if (const ConstantInt *CB = dyn_cast(Cond))
323330 return 0;
324331 }
325332
326 Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
333 Constant *llvm::ConstantFoldExtractElementInstruction(LLVMContext &Context,
334 const Constant *Val,
327335 const Constant *Idx) {
328336 if (isa(Val)) // ee(undef, x) -> undef
329 return UndefValue::get(cast(Val->getType())->getElementType());
337 return Context.getUndef(cast(Val->getType())->getElementType());
330338 if (Val->isNullValue()) // ee(zero, x) -> zero
331 return Constant::getNullValue(
339 return Context.getNullValue(
332340 cast(Val->getType())->getElementType());
333341
334342 if (const ConstantVector *CVal = dyn_cast(Val)) {
342350 return 0;
343351 }
344352
345 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
353 Constant *llvm::ConstantFoldInsertElementInstruction(LLVMContext &Context,
354 const Constant *Val,
346355 const Constant *Elt,
347356 const Constant *Idx) {
348357 const ConstantInt *CIdx = dyn_cast(Idx);
361370 Ops.reserve(numOps);
362371 for (unsigned i = 0; i < numOps; ++i) {
363372 const Constant *Op =
364 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
373 (idxVal == i) ? Elt : Context.getUndef(Elt->getType());
365374 Ops.push_back(const_cast(Op));
366375 }
367 return ConstantVector::get(Ops);
376 return Context.getConstantVector(Ops);
368377 }
369378 if (isa(Val)) {
370379 // Insertion of scalar constant into vector aggregate zero
379388 Ops.reserve(numOps);
380389 for (unsigned i = 0; i < numOps; ++i) {
381390 const Constant *Op =
382 (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
391 (idxVal == i) ? Elt : Context.getNullValue(Elt->getType());
383392 Ops.push_back(const_cast(Op));
384393 }
385 return ConstantVector::get(Ops);
394 return Context.getConstantVector(Ops);
386395 }
387396 if (const ConstantVector *CVal = dyn_cast(Val)) {
388397 // Insertion of scalar constant into vector constant
393402 (idxVal == i) ? Elt : cast(CVal->getOperand(i));
394403 Ops.push_back(const_cast(Op));
395404 }
396 return ConstantVector::get(Ops);
405 return Context.getConstantVector(Ops);
397406 }
398407
399408 return 0;
401410
402411 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
403412 /// return the specified element value. Otherwise return null.
404 static Constant *GetVectorElement(const Constant *C, unsigned EltNo) {
413 static Constant *GetVectorElement(LLVMContext &Context, const Constant *C,
414 unsigned EltNo) {
405415 if (const ConstantVector *CV = dyn_cast(C))
406416 return CV->getOperand(EltNo);
407417
408418 const Type *EltTy = cast(C->getType())->getElementType();
409419 if (isa(C))
410 return Constant::getNullValue(EltTy);
420 return Context.getNullValue(EltTy);
411421 if (isa(C))
412 return UndefValue::get(EltTy);
422 return Context.getUndef(EltTy);
413423 return 0;
414424 }
415425
416 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
426 Constant *llvm::ConstantFoldShuffleVectorInstruction(LLVMContext &Context,
427 const Constant *V1,
417428 const Constant *V2,
418429 const Constant *Mask) {
419430 // Undefined shuffle mask -> undefined value.
420 if (isa(Mask)) return UndefValue::get(V1->getType());
431 if (isa(Mask)) return Context.getUndef(V1->getType());
421432
422433 unsigned MaskNumElts = cast(Mask->getType())->getNumElements();
423434 unsigned SrcNumElts = cast(V1->getType())->getNumElements();
426437 // Loop over the shuffle mask, evaluating each element.
427438 SmallVector Result;
428439 for (unsigned i = 0; i != MaskNumElts; ++i) {
429 Constant *InElt = GetVectorElement(Mask, i);
440 Constant *InElt = GetVectorElement(Context, Mask, i);
430441 if (InElt == 0) return 0;
431442
432443 if (isa(InElt))
433 InElt = UndefValue::get(EltTy);
444 InElt = Context.getUndef(EltTy);
434445 else if (ConstantInt *CI = dyn_cast(InElt)) {
435446 unsigned Elt = CI->getZExtValue();
436447 if (Elt >= SrcNumElts*2)
437 InElt = UndefValue::get(EltTy);
448 InElt = Context.getUndef(EltTy);
438449 else if (Elt >= SrcNumElts)
439 InElt = GetVectorElement(V2, Elt - SrcNumElts);
450 InElt = GetVectorElement(Context, V2, Elt - SrcNumElts);
440451 else
441 InElt = GetVectorElement(V1, Elt);
452 InElt = GetVectorElement(Context, V1, Elt);
442453 if (InElt == 0) return 0;
443454 } else {
444455 // Unknown value.
447458 Result.push_back(InElt);
448459 }
449460
450 return ConstantVector::get(&Result[0], Result.size());
451 }
452
453 Constant *llvm::ConstantFoldExtractValueInstruction(const Constant *Agg,
461 return Context.getConstantVector(&Result[0], Result.size());
462 }
463
464 Constant *llvm::ConstantFoldExtractValueInstruction(LLVMContext &Context,
465 const Constant *Agg,
454466 const unsigned *Idxs,
455467 unsigned NumIdx) {
456468 // Base case: no indices, so return the entire value.
458470 return const_cast(Agg);
459471
460472 if (isa(Agg)) // ev(undef, x) -> undef
461 return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
473 return Context.getUndef(ExtractValueInst::getIndexedType(Agg->getType(),
462474 Idxs,
463475 Idxs + NumIdx));
464476
465477 if (isa(Agg)) // ev(0, x) -> 0
466478 return
467 Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
479 Context.getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
468480 Idxs,
469481 Idxs + NumIdx));
470482
471483 // Otherwise recurse.
472 return ConstantFoldExtractValueInstruction(Agg->getOperand(*Idxs),
484 return ConstantFoldExtractValueInstruction(Context, Agg->getOperand(*Idxs),
473485 Idxs+1, NumIdx-1);
474486 }
475487
476 Constant *llvm::ConstantFoldInsertValueInstruction(const Constant *Agg,
488 Constant *llvm::ConstantFoldInsertValueInstruction(LLVMContext &Context,
489 const Constant *Agg,
477490 const Constant *Val,
478491 const unsigned *Idxs,
479492 unsigned NumIdx) {
499512 const Type *MemberTy = AggTy->getTypeAtIndex(i);
500513 const Constant *Op =
501514 (*Idxs == i) ?
502 ConstantFoldInsertValueInstruction(UndefValue::get(MemberTy),
515 ConstantFoldInsertValueInstruction(Context, Context.getUndef(MemberTy),
503516 Val, Idxs+1, NumIdx-1) :
504 UndefValue::get(MemberTy);
517 Context.getUndef(MemberTy);
505518 Ops[i] = const_cast(Op);
506519 }
507520 if (isa(AggTy))
508 return ConstantStruct::get(Ops);
521 return Context.getConstantStruct(Ops);
509522 else
510 return ConstantArray::get(cast(AggTy), Ops);
523 return Context.getConstantArray(cast(AggTy), Ops);
511524 }
512525 if (isa(Agg)) {
513526 // Insertion of constant into aggregate zero
527540 const Type *MemberTy = AggTy->getTypeAtIndex(i);
528541 const Constant *Op =
529542 (*Idxs == i) ?
530 ConstantFoldInsertValueInstruction(Constant::getNullValue(MemberTy),
543 ConstantFoldInsertValueInstruction(Context,
544 Context.getNullValue(MemberTy),
531545 Val, Idxs+1, NumIdx-1) :
532 Constant::getNullValue(MemberTy);
546 Context.getNullValue(MemberTy);
533547 Ops[i] = const_cast(Op);
534548 }
535549 if (isa(AggTy))
536 return ConstantStruct::get(Ops);
550 return Context.getConstantStruct(Ops);
537551 else
538 return ConstantArray::get(cast(AggTy), Ops);
552 return Context.getConstantArray(cast(AggTy), Ops);
539553 }
540554 if (isa(Agg) || isa(Agg)) {
541555 // Insertion of constant into aggregate constant
543557 for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
544558 const Constant *Op =
545559 (*Idxs == i) ?
546 ConstantFoldInsertValueInstruction(Agg->getOperand(i),
560 ConstantFoldInsertValueInstruction(Context, Agg->getOperand(i),
547561 Val, Idxs+1, NumIdx-1) :
548562 Agg->getOperand(i);
549563 Ops[i] = const_cast(Op);
550564 }
551565 Constant *C;
552566 if (isa(Agg->getType()))
553 C = ConstantStruct::get(Ops);
567 C = Context.getConstantStruct(Ops);
554568 else
555 C = ConstantArray::get(cast(Agg->getType()), Ops);
569 C = Context.getConstantArray(cast(Agg->getType()), Ops);
556570 return C;
557571 }
558572
563577 /// function pointer to each element pair, producing a new ConstantVector
564578 /// constant. Either or both of V1 and V2 may be NULL, meaning a
565579 /// ConstantAggregateZero operand.
566 static Constant *EvalVectorOp(const ConstantVector *V1,
580 static Constant *EvalVectorOp(LLVMContext &Context, const ConstantVector *V1,
567581 const ConstantVector *V2,
568582 const VectorType *VTy,
569583 Constant *(*FP)(Constant*, Constant*)) {
570584 std::vector Res;
571585 const Type *EltTy = VTy->getElementType();
572586 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
573 const Constant *C1 = V1 ? V1->getOperand(i) : Constant::getNullValue(EltTy);
574 const Constant *C2 = V2 ? V2->getOperand(i) : Constant::getNullValue(EltTy);
587 const Constant *C1 = V1 ? V1->getOperand(i) : Context.getNullValue(EltTy);
588 const Constant *C2 = V2 ? V2->getOperand(i) : Context.getNullValue(EltTy);
575589 Res.push_back(FP(const_cast(C1),
576590 const_cast(C2)));
577591 }
578 return ConstantVector::get(Res);
579 }
580
581 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
592 return Context.getConstantVector(Res);
593 }
594
595 Constant *llvm::ConstantFoldBinaryInstruction(LLVMContext &Context,
596 unsigned Opcode,
582597 const Constant *C1,
583598 const Constant *C2) {
584599 // No compile-time operations on this type yet.
592607 if (isa(C1) && isa(C2))
593608 // Handle undef ^ undef -> 0 special case. This is a common
594609 // idiom (misuse).
595 return Constant::getNullValue(C1->getType());
610 return Context.getNullValue(C1->getType());
596611 // Fallthrough
597612 case Instruction::Add:
598613 case Instruction::Sub:
599 return UndefValue::get(C1->getType());
614 return Context.getUndef(C1->getType());
600615 case Instruction::Mul:
601616 case Instruction::And:
602 return Constant::getNullValue(C1->getType());
617 return Context.getNullValue(C1->getType());
603618 case Instruction::UDiv:
604619 case Instruction::SDiv:
605620 case Instruction::URem:
606621 case Instruction::SRem:
607622 if (!isa(C2)) // undef / X -> 0
608 return Constant::getNullValue(C1->getType());
623 return Context.getNullValue(C1->getType());
609624 return const_cast(C2); // X / undef -> undef
610625 case Instruction::Or: // X | undef -> -1
611626 if (const VectorType *PTy = dyn_cast(C1->getType()))
612 return ConstantVector::getAllOnesValue(PTy);
613 return ConstantInt::getAllOnesValue(C1->getType());
627 return Context.getAllOnesValue(PTy);
628 return Context.getAllOnesValue(C1->getType());
614629 case Instruction::LShr:
615630 if (isa(C2) && isa(C1))
616631 return const_cast(C1); // undef lshr undef -> undef
617 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
632 return Context.getNullValue(C1->getType()); // X lshr undef -> 0
618633 // undef lshr X -> 0
619634 case Instruction::AShr:
620635 if (!isa(C2))
625640 return const_cast(C1); // X ashr undef --> X
626641 case Instruction::Shl:
627642 // undef << X -> 0 or X << undef -> 0
628 return Constant::getNullValue(C1->getType());
643 return Context.getNullValue(C1->getType());
629644 }
630645 }
631646
648663 if (CI2->equalsInt(1))
649664 return const_cast(C1); // X / 1 == X
650665 if (CI2->equalsInt(0))
651 return UndefValue::get(CI2->getType()); // X / 0 == undef
666 return Context.getUndef(CI2->getType()); // X / 0 == undef
652667 break;
653668 case Instruction::URem:
654669 case Instruction::SRem:
655670 if (CI2->equalsInt(1))
656 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
671 return Context.getNullValue(CI2->getType()); // X % 1 == 0
657672 if (CI2->equalsInt(0))
658 return UndefValue::get(CI2->getType()); // X % 0 == undef
673 return Context.getUndef(CI2->getType()); // X % 0 == undef
659674 break;
660675 case Instruction::And:
661676 if (CI2->isZero()) return const_cast(C2); // X & 0 == 0
690705
691706 // If checking bits we know are clear, return zero.
692707 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
693 return Constant::getNullValue(CI2->getType());
708 return Context.getNullValue(CI2->getType());
694709 }
695710 }
696711 }
707722 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
708723 if (const ConstantExpr *CE1 = dyn_cast(C1))
709724 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
710 return ConstantExpr::getLShr(const_cast(C1),
711 const_cast(C2));
725 return Context.getConstantExprLShr(const_cast(C1),
726 const_cast(C2));
712727 break;
713728 }
714729 }
723738 default:
724739 break;
725740 case Instruction::Add:
726 return ConstantInt::get(C1V + C2V);
741 return Context.getConstantInt(C1V + C2V);
727742 case Instruction::Sub:
728 return ConstantInt::get(C1V - C2V);
743 return Context.getConstantInt(C1V - C2V);
729744 case Instruction::Mul:
730 return ConstantInt::get(C1V * C2V);
745 return Context.getConstantInt(C1V * C2V);
731746 case Instruction::UDiv:
732747 assert(!CI2->isNullValue() && "Div by zero handled above");
733 return ConstantInt::get(C1V.udiv(C2V));
748 return Context.getConstantInt(C1V.udiv(C2V));
734749 case Instruction::SDiv:
735750 assert(!CI2->isNullValue() && "Div by zero handled above");
736751 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
737 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
738 return ConstantInt::get(C1V.sdiv(C2V));
752 return Context.getUndef(CI1->getType()); // MIN_INT / -1 -> undef
753 return Context.getConstantInt(C1V.sdiv(C2V));
739754 case Instruction::URem:
740755 assert(!CI2->isNullValue() && "Div by zero handled above");
741 return ConstantInt::get(C1V.urem(C2V));
756 return Context.getConstantInt(C1V.urem(C2V));
742757 case Instruction::SRem:
743758 assert(!CI2->isNullValue() && "Div by zero handled above");
744759 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
745 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
746 return ConstantInt::get(C1V.srem(C2V));
760 return Context.getUndef(CI1->getType()); // MIN_INT % -1 -> undef
761 return Context.getConstantInt(C1V.srem(C2V));
747762 case Instruction::And:
748 return ConstantInt::get(C1V & C2V);
763 return Context.getConstantInt(C1V & C2V);
749764 case Instruction::Or:
750 return ConstantInt::get(C1V | C2V);
765 return Context.getConstantInt(C1V | C2V);
751766 case Instruction::Xor:
752 return ConstantInt::get(C1V ^ C2V);
767 return Context.getConstantInt(C1V ^ C2V);
753768 case Instruction::Shl: {
754769 uint32_t shiftAmt = C2V.getZExtValue();
755770 if (shiftAmt < C1V.getBitWidth())
756 return ConstantInt::get(C1V.shl(shiftAmt));
771 return Context.getConstantInt(C1V.shl(shiftAmt));
757772 else
758 return UndefValue::get(C1->getType()); // too big shift is undef
773 return Context.getUndef(C1->getType()); // too big shift is undef
759774 }
760775 case Instruction::LShr: {
761776 uint32_t shiftAmt = C2V.getZExtValue();
762777 if (shiftAmt < C1V.getBitWidth())
763 return ConstantInt::get(C1V.lshr(shiftAmt));
778 return Context.getConstantInt(C1V.lshr(shiftAmt));
764779 else
765 return UndefValue::get(C1->getType()); // too big shift is undef
780 return Context.getUndef(C1->getType()); // too big shift is undef
766781 }
767782 case Instruction::AShr: {
768783 uint32_t shiftAmt = C2V.getZExtValue();
769784 if (shiftAmt < C1V.getBitWidth())
770 return ConstantInt::get(C1V.ashr(shiftAmt));
785 return Context.getConstantInt(C1V.ashr(shiftAmt));
771786 else
772 return UndefValue::get(C1->getType()); // too big shift is undef
787 return Context.getUndef(C1->getType()); // too big shift is undef
773788 }
774789 }
775790 }
797812 break;
798813 case Instruction::FAdd:
799814 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
800 return ConstantFP::get(C3V);
815 return Context.getConstantFP(C3V);
801816 case Instruction::FSub:
802817 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
803 return ConstantFP::get(C3V);
818 return Context.getConstantFP(C3V);
804819 case Instruction::FMul:
805820 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
806 return ConstantFP::get(C3V);
821 return Context.getConstantFP(C3V);
807822 case Instruction::FDiv:
808823 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
809 return ConstantFP::get(C3V);
824 return Context.getConstantFP(C3V);
810825 case Instruction::FRem:
811826 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
812 return ConstantFP::get(C3V);
827 return Context.getConstantFP(C3V);
813828 }
814829 }
815830 } else if (const VectorType *VTy = dyn_cast(C1->getType())) {
821836 default:
822837 break;
823838 case Instruction::Add:
824 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAdd);
839 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getAdd);
825840 case Instruction::FAdd:
826 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFAdd);
841 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getFAdd);
827842 case Instruction::Sub:
828 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSub);
843 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getSub);
829844 case Instruction::FSub:
830 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFSub);
845 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getFSub);
831846 case Instruction::Mul:
832 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getMul);
847 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getMul);
833848 case Instruction::FMul:
834 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFMul);
849 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getFMul);
835850 case Instruction::UDiv:
836 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getUDiv);
851 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getUDiv);
837852 case Instruction::SDiv:
838 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSDiv);
853 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getSDiv);
839854 case Instruction::FDiv:
840 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFDiv);
855 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getFDiv);
841856 case Instruction::URem:
842 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getURem);
857 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getURem);
843858 case Instruction::SRem:
844 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSRem);
859 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getSRem);
845860 case Instruction::FRem:
846 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFRem);
861 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getFRem);
847862 case Instruction::And:
848 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAnd);
863 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getAnd);
849864 case Instruction::Or:
850 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getOr);
865 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getOr);
851866 case Instruction::Xor:
852 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getXor);
867 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getXor);
853868 case Instruction::LShr:
854 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getLShr);
869 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getLShr);
855870 case Instruction::AShr:
856 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAShr);
871 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getAShr);
857872 case Instruction::Shl:
858 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getShl);
873 return EvalVectorOp(Context, CP1, CP2, VTy, ConstantExpr::getShl);
859874 }
860875 }
861876 }
876891 case Instruction::Or:
877892 case Instruction::Xor:
878893 // No change of opcode required.
879 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
894 return ConstantFoldBinaryInstruction(Context, Opcode, C2, C1);
880895
881896 case Instruction::Shl:
882897 case Instruction::LShr:
922937 /// first is less than the second, return -1, if the second is less than the
923938 /// first, return 1. If the constants are not integral, return -2.
924939 ///
925 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
940 static int IdxCompare(LLVMContext &Context, Constant *C1, Constant *C2,
941 const Type *ElTy) {
926942 if (C1 == C2) return 0;
927943
928944 // Ok, we found a different index. If they are not ConstantInt, we can't do
933949 // Ok, we have two differing integer indices. Sign extend them to be the same
934950 // type. Long is always big enough, so we use it.
935951 if (C1->getType() != Type::Int64Ty)
936 C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
952 C1 = Context.getConstantExprSExt(C1, Type::Int64Ty);
937953
938954 if (C2->getType() != Type::Int64Ty)
939 C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
955 C2 = Context.getConstantExprSExt(C2, Type::Int64Ty);
940956
941957 if (C1 == C2) return 0; // They are equal
942958
965981 /// To simplify this code we canonicalize the relation so that the first
966982 /// operand is always the most "complex" of the two. We consider ConstantFP
967983 /// to be the simplest, and ConstantExprs to be the most complex.
968 static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1,
984 static FCmpInst::Predicate evaluateFCmpRelation(LLVMContext &Context,
985 const Constant *V1,
969986 const Constant *V2) {
970987 assert(V1->getType() == V2->getType() &&
971988 "Cannot compare values of different types!");
9841001 Constant *C1 = const_cast(V1);
9851002 Constant *C2 = const_cast(V2);
9861003 R = dyn_cast(
987 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
1004 Context.getConstantExprFCmp(FCmpInst::FCMP_OEQ, C1, C2));
9881005 if (R && !R->isZero())
9891006 return FCmpInst::FCMP_OEQ;
9901007 R = dyn_cast(
991 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
1008 Context.getConstantExprFCmp(FCmpInst::FCMP_OLT, C1, C2));
9921009 if (R && !R->isZero())
9931010 return FCmpInst::FCMP_OLT;
9941011 R = dyn_cast(
995 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
1012 Context.getConstantExprFCmp(FCmpInst::FCMP_OGT, C1, C2));
9961013 if (R && !R->isZero())
9971014 return FCmpInst::FCMP_OGT;
9981015
10011018 }
10021019
10031020 // If the first operand is simple and second is ConstantExpr, swap operands.
1004 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1021 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(Context, V2, V1);
10051022 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
10061023 return FCmpInst::getSwappedPredicate(SwappedRelation);
10071024 } else {
10361053 /// constants (like ConstantInt) to be the simplest, followed by
10371054 /// GlobalValues, followed by ConstantExpr's (the most complex).
10381055 ///
1039 static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1,
1056 static ICmpInst::Predicate evaluateICmpRelation(LLVMContext &Context,
1057 const Constant *V1,
10401058 const Constant *V2,
10411059 bool isSigned) {
10421060 assert(V1->getType() == V2->getType() &&
10511069 Constant *C1 = const_cast(V1);
10521070 Constant *C2 = const_cast(V2);
10531071 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1054 R = dyn_cast(ConstantExpr::getICmp(pred, C1, C2));
1072 R = dyn_cast(Context.getConstantExprICmp(pred, C1, C2));
10551073 if (R && !R->isZero())
10561074 return pred;
10571075 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1058 R = dyn_cast(ConstantExpr::getICmp(pred, C1, C2));
1076 R = dyn_cast(Context.getConstantExprICmp(pred, C1, C2));
10591077 if (R && !R->isZero())
10601078 return pred;
10611079 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1062 R = dyn_cast(ConstantExpr::getICmp(pred, C1, C2));
1080 R = dyn_cast(Context.getConstantExprICmp(pred, C1, C2));
10631081 if (R && !R->isZero())
10641082 return pred;
10651083
10691087
10701088 // If the first operand is simple, swap operands.
10711089 ICmpInst::Predicate SwappedRelation =
1072 evaluateICmpRelation(V2, V1, isSigned);
1090 evaluateICmpRelation(Context, V2, V1, isSigned);
10731091 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
10741092 return ICmpInst::getSwappedPredicate(SwappedRelation);
10751093
10761094 } else if (const GlobalValue *CPR1 = dyn_cast(V1)) {
10771095 if (isa(V2)) { // Swap as necessary.
10781096 ICmpInst::Predicate SwappedRelation =
1079 evaluateICmpRelation(V2, V1, isSigned);
1097 evaluateICmpRelation(Context, V2, V1, isSigned);
10801098 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
10811099 return ICmpInst::getSwappedPredicate(SwappedRelation);
10821100 else
11221140 bool sgnd = isSigned;
11231141 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
11241142 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1125 return evaluateICmpRelation(CE1Op0,
1126 Constant::getNullValue(CE1Op0->getType()),
1143 return evaluateICmpRelation(Context, CE1Op0,
1144 Context.getNullValue(CE1Op0->getType()),
11271145 sgnd);
11281146 }
11291147
11381156 bool sgnd = isSigned;
11391157 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
11401158 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1141 return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
1142 sgnd);
1159 return evaluateICmpRelation(Context, CE1->getOperand(0),
1160 CE2->getOperand(0), sgnd);
11431161 }
11441162 break;
11451163
12181236 gep_type_iterator GTI = gep_type_begin(CE1);
12191237 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
12201238 ++i, ++GTI)
1221 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1222 GTI.getIndexedType())) {
1239 switch (IdxCompare(Context, CE1->getOperand(i),
1240 CE2->getOperand(i), GTI.getIndexedType())) {
12231241 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
12241242 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
12251243 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
12541272 return ICmpInst::BAD_ICMP_PREDICATE;
12551273 }
12561274
1257 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1275 Constant *llvm::ConstantFoldCompareInstruction(LLVMContext &Context,
1276 unsigned short pred,
12581277 const Constant *C1,
12591278 const Constant *C2) {
12601279 const Type *ResultTy;
12611280 if (const VectorType *VT = dyn_cast(C1->getType()))
1262 ResultTy = VectorType::get(Type::Int1Ty, VT->getNumElements());
1281 ResultTy = Context.getVectorType(Type::Int1Ty, VT->getNumElements());
12631282 else
12641283 ResultTy = Type::Int1Ty;
12651284
12661285 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
12671286 if (pred == FCmpInst::FCMP_FALSE)
1268 return Constant::getNullValue(ResultTy);
1287 return Context.getNullValue(ResultTy);
12691288
12701289 if (pred == FCmpInst::FCMP_TRUE)
1271 return Constant::getAllOnesValue(ResultTy);
1290 return Context.getAllOnesValue(ResultTy);
12721291
12731292 // Handle some degenerate cases first
12741293 if (isa(C1) || isa(C2))
1275 return UndefValue::get(ResultTy);
1294 return Context.getUndef(ResultTy);
12761295
12771296 // No compile-time operations on this type yet.
12781297 if (C1->getType() == Type::PPC_FP128Ty)
12841303 // Don't try to evaluate aliases. External weak GV can be null.
12851304 if (!isa(GV) && !GV->hasExternalWeakLinkage()) {
12861305 if (pred == ICmpInst::ICMP_EQ)
1287 return ConstantInt::getFalse();
1306 return Context.getConstantIntFalse();
12881307 else if (pred == ICmpInst::ICMP_NE)
1289 return ConstantInt::getTrue();
1308 return Context.getConstantIntTrue();
12901309 }
12911310 // icmp eq/ne(GV,null) -> false/true
12921311 } else if (C2->isNullValue()) {
12941313 // Don't try to evaluate aliases. External weak GV can be null.
12951314 if (!isa(GV) && !GV->hasExternalWeakLinkage()) {
12961315 if (pred == ICmpInst::ICMP_EQ)
1297 return ConstantInt::getFalse();
1316 return Context.getConstantIntFalse();
12981317 else if (pred == ICmpInst::ICMP_NE)
1299 return ConstantInt::getTrue();
1318 return Context.getConstantIntTrue();
13001319 }
13011320 }
13021321
13051324 APInt V2 = cast(C2)->getValue();
13061325 switch (pred) {
13071326 default: LLVM_UNREACHABLE("Invalid ICmp Predicate"); return 0;
1308 case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1309 case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1310 case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1.slt(V2));
1311 case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1.sgt(V2));
1312 case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1.sle(V2));
1313 case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1.sge(V2));
1314 case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1.ult(V2));
1315 case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1.ugt(V2));
1316 case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1.ule(V2));
1317 case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1.uge(V2));
1327 case ICmpInst::ICMP_EQ:
1328 return Context.getConstantInt(Type::Int1Ty, V1 == V2);
1329 case ICmpInst::ICMP_NE:
1330 return Context.getConstantInt(Type::Int1Ty, V1 != V2);
1331 case ICmpInst::ICMP_SLT:
1332 return Context.getConstantInt(Type::Int1Ty, V1.slt(V2));
1333 case ICmpInst::ICMP_SGT:
1334 return Context.getConstantInt(Type::Int1Ty, V1.sgt(V2));
1335 case ICmpInst::ICMP_SLE:
1336 return Context.getConstantInt(Type::Int1Ty, V1.sle(V2));
1337 case ICmpInst::ICMP_SGE:
1338 return Context.getConstantInt(Type::Int1Ty, V1.sge(V2));
1339 case ICmpInst::ICMP_ULT:
1340 return Context.getConstantInt(Type::Int1Ty, V1.ult(V2));
1341 case ICmpInst::ICMP_UGT:
1342 return Context.getConstantInt(Type::Int1Ty, V1.ugt(V2));
1343 case ICmpInst::ICMP_ULE:
1344 return Context.getConstantInt(Type::Int1Ty, V1.ule(V2));
1345 case ICmpInst::ICMP_UGE:
1346 return Context.getConstantInt(Type::Int1Ty, V1.uge(V2));
13181347 }
13191348 } else if (isa(C1) && isa(C2)) {
13201349 APFloat C1V = cast(C1)->getValueAPF();
13221351 APFloat::cmpResult R = C1V.compare(C2V);
13231352 switch (pred) {
13241353 default: LLVM_UNREACHABLE("Invalid FCmp Predicate"); return 0;
1325 case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1326 case FCmpInst::FCMP_TRUE: return ConstantInt::getTrue();
1354 case FCmpInst::FCMP_FALSE: return Context.getConstantIntFalse();
1355 case FCmpInst::FCMP_TRUE: return Context.getConstantIntTrue();
13271356 case FCmpInst::FCMP_UNO:
1328 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered);
1357 return Context.getConstantInt(Type::Int1Ty, R==APFloat::cmpUnordered);
13291358 case FCmpInst::FCMP_ORD:
1330 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpUnordered);
1359 return Context.getConstantInt(Type::Int1Ty, R!=APFloat::cmpUnordered);
13311360 case FCmpInst::FCMP_UEQ:
1332 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1361 return Context.getConstantInt(Type::Int1Ty, R==APFloat::cmpUnordered ||
13331362 R==APFloat::cmpEqual);
13341363 case FCmpInst::FCMP_OEQ:
1335 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpEqual);
1364 return Context.getConstantInt(Type::Int1Ty, R==APFloat::cmpEqual);
13361365 case FCmpInst::FCMP_UNE:
1337 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpEqual);
1366 return Context.getConstantInt(Type::Int1Ty, R!=APFloat::cmpEqual);
13381367 case FCmpInst::FCMP_ONE:
1339 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1368 return Context.getConstantInt(Type::Int1Ty, R==APFloat::cmpLessThan ||
13401369 R==APFloat::cmpGreaterThan);
13411370 case FCmpInst::FCMP_ULT:
1342 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1371 return Context.getConstantInt(Type::Int1Ty, R==APFloat::cmpUnordered ||
13431372 R==APFloat::cmpLessThan);
13441373 case FCmpInst::FCMP_OLT:
1345 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan);
1374 return Context.getConstantInt(Type::Int1Ty, R==APFloat::cmpLessThan);
13461375 case FCmpInst::FCMP_UGT:
1347 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1376 return Context.getConstantInt(Type::Int1Ty, R==APFloat::cmpUnordered ||
13481377 R==APFloat::cmpGreaterThan);
13491378 case FCmpInst::FCMP_OGT:
1350 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan);
1379 return Context.getConstantInt(Type::Int1Ty, R==APFloat::cmpGreaterThan);
13511380 case FCmpInst::FCMP_ULE:
1352 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpGreaterThan);
1381 return Context.getConstantInt(Type::Int1Ty, R!=APFloat::cmpGreaterThan);
13531382 case FCmpInst::FCMP_OLE:
1354 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1383 return Context.getConstantInt(Type::Int1Ty, R==APFloat::cmpLessThan ||
13551384 R==APFloat::cmpEqual);
13561385 case FCmpInst::FCMP_UGE:
1357 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpLessThan);
1386 return Context.getConstantInt(Type::Int1Ty, R!=APFloat::cmpLessThan);
13581387 case FCmpInst::FCMP_OGE:
1359 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan ||
1388 return Context.getConstantInt(Type::Int1Ty, R==APFloat::cmpGreaterThan ||
13601389 R==APFloat::cmpEqual);
13611390 }
13621391 } else if (isa(C1->getType())) {
13631392 SmallVector C1Elts, C2Elts;
1364 C1->getVectorElements(C1Elts);
1365 C2->getVectorElements(C2Elts);
1393 C1->getVectorElements(Context, C1Elts);
1394 C2->getVectorElements(Context, C2Elts);
13661395
13671396 // If we can constant fold the comparison of each element, constant fold
13681397 // the whole vector comparison.
13691398 SmallVector ResElts;
13701399 for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
13711400 // Compare the elements, producing an i1 result or constant expr.
1372 ResElts.push_back(ConstantExpr::getCompare(pred, C1Elts[i], C2Elts[i]));
1373 }
1374 return ConstantVector::get(&ResElts[0], ResElts.size());
1401 ResElts.push_back(
1402 Context.getConstantExprCompare(pred, C1Elts[i], C2Elts[i]));
1403 }
1404 return Context.getConstantVector(&ResElts[0], ResElts.size());
13751405 }
13761406
13771407 if (C1->getType()->isFloatingPoint()) {
13781408 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1379 switch (evaluateFCmpRelation(C1, C2)) {
1409 switch (evaluateFCmpRelation(Context, C1, C2)) {
13801410 default: LLVM_UNREACHABLE("Unknown relation!");
13811411 case FCmpInst::FCMP_UNO:
13821412 case FCmpInst::FCMP_ORD:
14301460
14311461 // If we evaluated the result, return it now.
14321462 if (Result != -1)
1433 return ConstantInt::get(Type::Int1Ty, Result);
1463 return Context.getConstantInt(Type::Int1Ty, Result);
14341464
14351465 } else {
14361466 // Evaluate the relation between the two constants, per the predicate.
14371467 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1438 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1468 switch (evaluateICmpRelation(Context, C1, C2, CmpInst::isSigned(pred))) {
14391469 default: LLVM_UNREACHABLE("Unknown relational!");
14401470 case ICmpInst::BAD_ICMP_PREDICATE:
14411471 break; // Couldn't determine anything about these constants.
15071537
15081538 // If we evaluated the result, return it now.
15091539 if (Result != -1)
1510 return ConstantInt::get(Type::Int1Ty, Result);
1540 return Context.getConstantInt(Type::Int1Ty, Result);
15111541
15121542 if (!isa(C1) && isa(C2)) {
15131543 // If C2 is a constant expr and C1 isn't, flip them around and fold the
15161546 case ICmpInst::ICMP_EQ:
15171547 case ICmpInst::ICMP_NE:
15181548 // No change of predicate required.
1519 return ConstantFoldCompareInstruction(pred, C2, C1);
1549 return ConstantFoldCompareInstruction(Context, pred, C2, C1);
15201550
15211551 case ICmpInst::ICMP_ULT:
15221552 case ICmpInst::ICMP_SLT:
15281558 case ICmpInst::ICMP_SGE:
15291559 // Change the predicate as necessary to swap the operands.
15301560 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1531 return ConstantFoldCompareInstruction(pred, C2, C1);
1561 return ConstantFoldCompareInstruction(Context, pred, C2, C1);
15321562
15331563 default: // These predicates cannot be flopped around.
15341564 break;
15381568 return 0;
15391569 }
15401570
1541 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1571 Constant *llvm::ConstantFoldGetElementPtr(LLVMContext &Context,
1572 const Constant *C,
15421573 Constant* const *Idxs,
15431574 unsigned NumIdx) {
15441575 if (NumIdx == 0 ||
15511582 (Value **)Idxs,
15521583 (Value **)Idxs+NumIdx);
15531584 assert(Ty != 0 && "Invalid indices for GEP!");
1554 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1585 return Context.getUndef(Context.getPointerType(Ty, Ptr->getAddressSpace()));
15551586 }
15561587
15571588 Constant *Idx0 = Idxs[0];
15681599 (Value**)Idxs,
15691600 (Value**)Idxs+NumIdx);
15701601 assert(Ty != 0 && "Invalid indices for GEP!");
1571 return
1572 ConstantPointerNull::get(PointerType::get(Ty,Ptr->getAddressSpace()));
1602 return Context.getConstantPointerNull(
1603 Context.getPointerType(Ty,Ptr->getAddressSpace()));
15731604 }
15741605 }
15751606
15971628 if (!Idx0->isNullValue()) {
15981629 const Type *IdxTy = Combined->getType();
15991630 if (IdxTy != Idx0->getType()) {
1600 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
1601 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
1631 Constant *C1 =
1632 Context.getConstantExprSExtOrBitCast(Idx0, Type::Int64Ty);
1633 Constant *C2 = Context.getConstantExprSExtOrBitCast(Combined,
16021634 Type::Int64Ty);
1603 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1635 Combined = Context.getConstantExpr(Instruction::Add, C1, C2);
16041636 } else {
16051637 Combined =
1606 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1638 Context.getConstantExpr(Instruction::Add, Idx0, Combined);
16071639 }
16081640 }
16091641
16101642 NewIndices.push_back(Combined);
16111643 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1612 return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1644 return Context.getConstantExprGetElementPtr(CE->getOperand(0),
1645 &NewIndices[0],
16131646 NewIndices.size());
16141647 }
16151648 }
16261659 if (const ArrayType *CAT =
16271660 dyn_cast(cast(C->getType())->getElementType()))
16281661 if (CAT->getElementType() == SAT->getElementType())
1629 return ConstantExpr::getGetElementPtr(
1662 return Context.getConstantExprGetElementPtr(
16301663 (Constant*)CE->getOperand(0), Idxs, NumIdx);
16311664 }
16321665
16421675 // Convert the smaller integer to the larger type.
16431676 if (Offset->getType()->getPrimitiveSizeInBits() <
16441677 Base->getType()->getPrimitiveSizeInBits())
1645 Offset = ConstantExpr::getSExt(Offset, Base->getType());
1678 Offset = Context.getConstantExprSExt(Offset, Base->getType());
16461679 else if (Base->getType()->getPrimitiveSizeInBits() <
16471680 Offset->getType()->getPrimitiveSizeInBits())
1648 Base = ConstantExpr::getZExt(Base, Offset->getType());
1681 Base = Context.getConstantExprZExt(Base, Offset->getType());
16491682
1650 Base = ConstantExpr::getAdd(Base, Offset);
1651 return ConstantExpr::getIntToPtr(Base, CE->getType());
1683 Base = Context.getConstantExprAdd(Base, Offset);
1684 return Context.getConstantExprIntToPtr(Base, CE->getType());
16521685 }
16531686 }
16541687 return 0;
2222 class Value;
2323 class Constant;
2424 class Type;
25 class LLVMContext;
2526
2627 // Constant fold various types of instruction...
2728 Constant *ConstantFoldCastInstruction(
29 LLVMContext &Context,
2830 unsigned opcode, ///< The opcode of the cast
2931 const Constant *V, ///< The source constant
3032 const Type *DestTy ///< The destination type
3133 );
32 Constant *ConstantFoldSelectInstruction(const Constant *Cond,
34 Constant *ConstantFoldSelectInstruction(LLVMContext &Context,
35 const Constant *Cond,
3336 const Constant *V1,
3437 const Constant *V2);
35 Constant *ConstantFoldExtractElementInstruction(const Constant *Val,
38 Constant *ConstantFoldExtractElementInstruction(LLVMContext &Context,
39 const Constant *Val,
3640 const Constant *Idx);
37 Constant *ConstantFoldInsertElementInstruction(const Constant *Val,
41 Constant *ConstantFoldInsertElementInstruction(LLVMContext &Context,
42 const Constant *Val,
3843 const Constant *Elt,
3944 const Constant *Idx);
40 Constant *ConstantFoldShuffleVectorInstruction(const Constant *V1,
45 Constant *ConstantFoldShuffleVectorInstruction(LLVMContext &Context,
46 const Constant *V1,
4147 const Constant *V2,
4248 const Constant *Mask);
43 Constant *ConstantFoldExtractValueInstruction(const Constant *Agg,
49 Constant *ConstantFoldExtractValueInstruction(LLVMContext &Context,
50 const Constant *Agg,
4451 const unsigned *Idxs,
4552 unsigned NumIdx);
46 Constant *ConstantFoldInsertValueInstruction(const Constant *Agg,
53 Constant *ConstantFoldInsertValueInstruction(LLVMContext &Context,
54 const Constant *Agg,
4755 const Constant *Val,
4856 const unsigned* Idxs,
4957 unsigned NumIdx);
50 Constant *ConstantFoldBinaryInstruction(unsigned Opcode, const Constant *V1,
58 Constant *ConstantFoldBinaryInstruction(LLVMContext &Context,
59 unsigned Opcode, const Constant *V1,
5160 const Constant *V2);
52 Constant *ConstantFoldCompareInstruction(unsigned short predicate,
61 Constant *ConstantFoldCompareInstruction(LLVMContext &Context,
62 unsigned short predicate,
5363 const Constant *C1,
5464 const Constant *C2);
55 Constant *ConstantFoldGetElementPtr(const Constant *C,
65 Constant *ConstantFoldGetElementPtr(LLVMContext &Context, const Constant *C,
5666 Constant* const *Idxs, unsigned NumIdx);
5767 } // End llvm namespace
5868
127127 return false;
128128 }
129129
130 // Static constructor to create a '0' constant of arbitrary type...
131 static const uint64_t zero[2] = {0, 0};
132 Constant *Constant::getNullValue(const Type *Ty) {
133 switch (Ty->getTypeID()) {
134 case Type::IntegerTyID:
135 return ConstantInt::get(Ty, 0);
136 case Type::FloatTyID:
137 return ConstantFP::get(APFloat(APInt(32, 0)));
138 case Type::DoubleTyID:
139 return ConstantFP::get(APFloat(APInt(64, 0)));
140 case Type::X86_FP80TyID:
141 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
142 case Type::FP128TyID:
143 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
144 case Type::PPC_FP128TyID:
145 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
146 case Type::PointerTyID:
147 return ConstantPointerNull::get(cast(Ty));
148 case Type::StructTyID:
149 case Type::ArrayTyID:
150 case Type::VectorTyID:
151 return ConstantAggregateZero::get(Ty);
152 default:
153 // Function, Label, or Opaque type?
154 assert(!"Cannot create a null constant of that type!");
155 return 0;
156 }
157 }
158
159130 Constant *Constant::getAllOnesValue(const Type *Ty) {
160131 if (const IntegerType* ITy = dyn_cast(Ty))
161132 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
185156 /// type, returns the elements of the vector in the specified smallvector.
186157 /// This handles breaking down a vector undef into undef elements, etc. For
187158 /// constant exprs and other cases we can't handle, we return an empty vector.
188 void Constant::getVectorElements(SmallVectorImpl &Elts) const {
159 void Constant::getVectorElements(LLVMContext &Context,
160 SmallVectorImpl &Elts) const {
189161 assert(isa(getType()) && "Not a vector constant!");
190162
191163 if (const ConstantVector *CV = dyn_cast(this)) {
197169 const VectorType *VT = cast(getType());
198170 if (isa(this)) {
199171 Elts.assign(VT->getNumElements(),
200 Constant::getNullValue(VT->getElementType()));
172 Context.getNullValue(VT->getElementType()));
201173 return;
202174 }
203175
204176 if (isa(this)) {
205 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
177 Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
206178 return;
207179 }
208180
358330
359331 bool ConstantFP::isNullValue() const {
360332 return Val.isZero() && !Val.isNegative();
361 }
362
363 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
364 APFloat apf = cast (Constant::getNullValue(Ty))->getValueAPF();
365 apf.changeSign();
366 return ConstantFP::get(apf);
367333 }
368334
369335 bool ConstantFP::isExactlyValue(const APFloat& V) const {
830796 return cast(this)->Indices;
831797 }
832798
833 /// ConstantExpr::get* - Return some common constants without having to
834 /// specify the full Instruction::OPCODE identifier.
835 ///
836 Constant *ConstantExpr::getNeg(Constant *C) {
837 // API compatibility: Adjust integer opcodes to floating-point opcodes.
838 if (C->getType()->isFPOrFPVector())
839 return getFNeg(C);
840 assert(C->getType()->isIntOrIntVector() &&
841 "Cannot NEG a nonintegral value!");
842 return get(Instruction::Sub,
843 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
844 C);
845 }
846 Constant *ConstantExpr::getFNeg(Constant *C) {
847 assert(C->getType()->isFPOrFPVector() &&
848 "Cannot FNEG a non-floating-point value!");
849 return get(Instruction::FSub,
850 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
851 C);
852 }
853799 Constant *ConstantExpr::getNot(Constant *C) {
854800 assert(C->getType()->isIntOrIntVector() &&
855801 "Cannot NOT a nonintegral value!");
15001446 /// isCString - This method returns true if the array is a string (see
15011447 /// isString) and it ends in a null byte \\0 and does not contains any other
15021448 /// null bytes except its terminator.
1503 bool ConstantArray::isCString() const {
1449 bool ConstantArray::isCString(LLVMContext &Context) const {
15041450 // Check the element type for i8...
15051451 if (getType()->getElementType() != Type::Int8Ty)
15061452 return false;
1507 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1453 Constant *Zero = Context.getNullValue(getOperand(0)->getType());
15081454 // Last element must be a null.
15091455 if (getOperand(getNumOperands()-1) != Zero)
15101456 return false;
20101956 Instruction::CastOps opc, Constant *C, const Type *Ty) {
20111957 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
20121958 // Fold a few common cases
2013 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1959 if (Constant *FC =
1960 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
20141961 return FC;
20151962
20161963 // Look up the constant in the table first to ensure uniqueness
22442191 return getFoldedCast(Instruction::BitCast, C, DstTy);
22452192 }
22462193
2247 Constant *ConstantExpr::getAlignOf(const Type *Ty) {
2248 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
2249 const Type *AligningTy = StructType::get(Type::Int8Ty, Ty, NULL);
2250 Constant *NullPtr = getNullValue(AligningTy->getPointerTo());
2251 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
2252 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
2253 Constant *Indices[2] = { Zero, One };
2254 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
2255 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
2256 }
2257
2258 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
2259 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2260 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2261 Constant *GEP =
2262 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
2263 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
2264 }
2265
22662194 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
22672195 Constant *C1, Constant *C2) {
22682196 // Check the operands for consistency first
22732201 "Operand types in binary constant expression should match");
22742202
22752203 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2276 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2204 if (Constant *FC = ConstantFoldBinaryInstruction(
2205 getGlobalContext(), Opcode, C1, C2))
22772206 return FC; // Fold a few common cases...
22782207
22792208 std::vector argVec(1, C1); argVec.push_back(C2);
23822311 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
23832312
23842313 if (ReqTy == V1->getType())
2385 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2314 if (Constant *SC = ConstantFoldSelectInstruction(
2315 getGlobalContext(), C, V1, V2))
23862316 return SC; // Fold common cases
23872317
23882318 std::vector argVec(3, C);
24022332 cast(ReqTy)->getElementType() &&
24032333 "GEP indices invalid!");
24042334
2405 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
2335 if (Constant *FC = ConstantFoldGetElementPtr(
2336 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
24062337 return FC; // Fold a few common cases...
24072338
24082339 assert(isa(C->getType()) &&
24412372 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
24422373 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
24432374
2444 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2375 if (Constant *FC = ConstantFoldCompareInstruction(
2376 getGlobalContext(),pred, LHS, RHS))
24452377 return FC; // Fold a few common cases...
24462378
24472379 // Look up the constant in the table first to ensure uniqueness
24602392 assert(LHS->getType() == RHS->getType());
24612393 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
24622394
2463 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2395 if (Constant *FC = ConstantFoldCompareInstruction(
2396 getGlobalContext(), pred, LHS, RHS))
24642397 return FC; // Fold a few common cases...
24652398
24662399 // Look up the constant in the table first to ensure uniqueness
24762409
24772410 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
24782411 Constant *Idx) {
2479 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2412 if (Constant *FC = ConstantFoldExtractElementInstruction(
2413 getGlobalContext(), Val, Idx))
24802414 return FC; // Fold a few common cases...
24812415 // Look up the constant in the table first to ensure uniqueness
24822416 std::vector ArgVec(1, Val);
24982432
24992433 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
25002434 Constant *Elt, Constant *Idx) {
2501 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2435 if (Constant *FC = ConstantFoldInsertElementInstruction(
2436 getGlobalContext(), Val, Elt, Idx))
25022437 return FC; // Fold a few common cases...
25032438 // Look up the constant in the table first to ensure uniqueness
25042439 std::vector ArgVec(1, Val);
25232458
25242459 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
25252460 Constant *V2, Constant *Mask) {
2526 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2461 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
2462 getGlobalContext(), V1, V2, Mask))
25272463 return FC; // Fold a few common cases...
25282464 // Look up the constant in the table first to ensure uniqueness
25292465 std::vector ArgVec(1, V1);
25562492 "insertvalue type invalid!");
25572493 assert(Agg->getType()->isFirstClassType() &&
25582494 "Non-first-class type for constant InsertValue expression");
2559 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2495 Constant *FC = ConstantFoldInsertValueInstruction(
2496 getGlobalContext(), Agg, Val, Idxs, NumIdx);
25602497 assert(FC && "InsertValue constant expr couldn't be folded!");
25612498 return FC;
25622499 }
25822519 "extractvalue indices invalid!");
25832520 assert(Agg->getType()->isFirstClassType() &&
25842521 "Non-first-class type for constant extractvalue expression");
2585 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2522 Constant *FC = ConstantFoldExtractValueInstruction(
2523 getGlobalContext(), Agg, Idxs, NumIdx);
25862524 assert(FC && "ExtractValue constant expr couldn't be folded!");
25872525 return FC;
25882526 }
25962534 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
25972535 assert(ReqTy && "extractvalue indices invalid!");
25982536 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2599 }
2600
2601 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2602 if (const VectorType *PTy = dyn_cast(Ty))
2603 if (PTy->getElementType()->isFloatingPoint()) {
2604 std::vector zeros(PTy->getNumElements(),
2605 ConstantFP::getNegativeZero(PTy->getElementType()));
2606 return ConstantVector::get(PTy, zeros);
2607 }
2608
2609 if (Ty->isFloatingPoint())
2610 return ConstantFP::getNegativeZero(Ty);
2611
2612 return Constant::getNullValue(Ty);
26132537 }
26142538
26152539 // destroyConstant - Remove the constant from the constant table...
16321632 return Res;
16331633 }
16341634
1635 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1635 BinaryOperator *BinaryOperator::CreateNeg(LLVMContext &Context,
1636 Value *Op, const std::string &Name,
16361637 Instruction *InsertBefore) {
1637 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1638 Value *zero = Context.getZeroValueForNegation(Op->getType());
16381639 return new BinaryOperator(Instruction::Sub,
16391640 zero, Op,
16401641 Op->getType(), Name, InsertBefore);
16411642 }
16421643
1643 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1644 BinaryOperator *BinaryOperator::CreateNeg(LLVMContext &Context,
1645 Value *Op, const std::string &Name,
16441646 BasicBlock *InsertAtEnd) {
1645 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1647 Value *zero = Context.getZeroValueForNegation(Op->getType());
16461648 return new BinaryOperator(Instruction::Sub,
16471649 zero, Op,
16481650 Op->getType(), Name, InsertAtEnd);
16491651 }
16501652
1651 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const std::string &Name,
1653 BinaryOperator *BinaryOperator::CreateFNeg(LLVMContext &Context,
1654 Value *Op, const std::string &Name,
16521655 Instruction *InsertBefore) {
1653 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1656 Value *zero = Context.getZeroValueForNegation(Op->getType());
16541657 return new BinaryOperator(Instruction::FSub,
16551658 zero, Op,
16561659 Op->getType(), Name, InsertBefore);
16571660 }
16581661
1659 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const std::string &Name,
1662 BinaryOperator *BinaryOperator::CreateFNeg(LLVMContext &Context,
1663 Value *Op, const std::string &Name,
16601664 BasicBlock *InsertAtEnd) {
1661 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1665 Value *zero = Context.getZeroValueForNegation(Op->getType());
16621666 return new BinaryOperator(Instruction::FSub,
16631667 zero, Op,
16641668 Op->getType(), Name, InsertAtEnd);
17041708 return false;
17051709 }
17061710
1707 bool BinaryOperator::isNeg(const Value *V) {
1711 bool BinaryOperator::isNeg(LLVMContext &Context, const Value *V) {
17081712 if (const BinaryOperator *Bop = dyn_cast(V))
17091713 if (Bop->getOpcode() == Instruction::Sub)
17101714 return Bop->getOperand(0) ==
1711 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1715 Context.getZeroValueForNegation(Bop->getType());
17121716 return false;
17131717 }
17141718
1715 bool BinaryOperator::isFNeg(const Value *V) {
1719 bool BinaryOperator::isFNeg(LLVMContext &Context, const Value *V) {
17161720 if (const BinaryOperator *Bop = dyn_cast(V))
17171721 if (Bop->getOpcode() == Instruction::FSub)
17181722 return Bop->getOperand(0) ==
1719 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1723 Context.getZeroValueForNegation(Bop->getType());
17201724 return false;
17211725 }
17221726
17291733 }
17301734
17311735 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1732 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
17331736 return cast(BinOp)->getOperand(1);
17341737 }
17351738
17381741 }
17391742
17401743 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1741 assert(isFNeg(BinOp) && "getFNegArgument from non-'fneg' instruction!");
17421744 return cast(BinOp)->getOperand(1);
17431745 }
17441746
1414 #include "llvm/LLVMContext.h"
1515 #include "llvm/Constants.h"
1616 #include "llvm/DerivedTypes.h"
17 #include "llvm/Instruction.h"
1718 #include "llvm/MDNode.h"
1819 #include "llvm/Support/ManagedStatic.h"
1920 #include "LLVMContextImpl.h"
3031 LLVMContext::~LLVMContext() { delete pImpl; }
3132
3233 // Constant accessors
34
35 // Constructor to create a '0' constant of arbitrary type...
36 static const uint64_t zero[2] = {0, 0};
3337 Constant* LLVMContext::getNullValue(const Type* Ty) {
34 return Constant::getNullValue(Ty);
38 switch (Ty->getTypeID()) {
39 case Type::IntegerTyID:
40 return getConstantInt(Ty, 0);
41 case Type::FloatTyID:
42 return getConstantFP(APFloat(APInt(32, 0)));
43 case Type::DoubleTyID:
44 return getConstantFP(APFloat(APInt(64, 0)));
45 case Type::X86_FP80TyID:
46 return getConstantFP(APFloat(APInt(80, 2, zero)));
47 case Type::FP128TyID:
48 return getConstantFP(APFloat(APInt(128, 2, zero), true));
49 case Type::PPC_FP128TyID:
50 return getConstantFP(APFloat(APInt(128, 2, zero)));
51 case Type::PointerTyID:
52 return getConstantPointerNull(cast(Ty));
53 case Type::StructTyID:
54 case Type::ArrayTyID:
55 case Type::VectorTyID:
56 return getConstantAggregateZero(Ty);
57 default:
58 // Function, Label, or Opaque type?
59 assert(!"Cannot create a null constant of that type!");
60 return 0;
61 }
3562 }
3663
3764 Constant* LLVMContext::getAllOnesValue(const Type* Ty) {
221248 }
222249
223250 Constant* LLVMContext::getConstantExprAlignOf(const Type* Ty) {
224 return ConstantExpr::getAlignOf(Ty);
251 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
252 const Type *AligningTy = getStructType(Type::Int8Ty, Ty, NULL);
253 Constant *NullPtr = getNullValue(AligningTy->getPointerTo());
254 Constant *Zero = getConstantInt(Type::Int32Ty, 0);
255 Constant *One = getConstantInt(Type::Int32Ty, 1);
256 Constant *Indices[2] = { Zero, One };
257 Constant *GEP = getConstantExprGetElementPtr(NullPtr, Indices, 2);
258 return getConstantExprCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
225259 }
226260
227261 Constant* LLVMContext::getConstantExprCompare(unsigned short pred,
230264 }
231265
232266 Constant* LLVMContext::getConstantExprNeg(Constant* C) {
233 return ConstantExpr::getNeg(C);
267 // API compatibility: Adjust integer opcodes to floating-point opcodes.
268 if (C->getType()->isFPOrFPVector())
269 return getConstantExprFNeg(C);
270 assert(C->getType()->isIntOrIntVector() &&
271 "Cannot NEG a nonintegral value!");
272 return getConstantExpr(Instruction::Sub,
273 getZeroValueForNegation(C->getType()),
274 C);
234275 }
235276
236277 Constant* LLVMContext::getConstantExprFNeg(Constant* C) {
237 return ConstantExpr::getFNeg(C);
278 assert(C->getType()->isFPOrFPVector() &&
279 "Cannot FNEG a non-floating-point value!");
280 return getConstantExpr(Instruction::FSub,
281 getZeroValueForNegation(C->getType()),
282 C);
238283 }
239284
240285 Constant* LLVMContext::getConstantExprNot(Constant* C) {
364409 }
365410
366411 Constant* LLVMContext::getConstantExprSizeOf(const Type* Ty) {
367 return ConstantExpr::getSizeOf(Ty);
412 // sizeof is implemented as: (i64) gep (Ty*)null, 1
413 Constant *GEPIdx = getConstantInt(Type::Int32Ty, 1);
414 Constant *GEP = getConstantExprGetElementPtr(
415 getNullValue(getPointerTypeUnqual(Ty)), &GEPIdx, 1);
416 return getConstantExprCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
368417 }
369418
370419 Constant* LLVMContext::getZeroValueForNegation(const Type* Ty) {
371 return ConstantExpr::getZeroValueForNegationExpr(Ty);
420 if (const VectorType *PTy = dyn_cast(Ty))
421 if (PTy->getElementType()->isFloatingPoint()) {
422 std::vector zeros(PTy->getNumElements(),
423 getConstantFPNegativeZero(PTy->getElementType()));
424 return getConstantVector(PTy, zeros);
425 }
426
427 if (Ty->isFloatingPoint())
428 return getConstantFPNegativeZero(Ty);
429
430 return getNullValue(Ty);
372431 }
373432
374433
382441 }
383442
384443 ConstantFP* LLVMContext::getConstantFPNegativeZero(const Type* Ty) {
385 return ConstantFP::getNegativeZero(Ty);
444 APFloat apf = cast (getNullValue(Ty))->getValueAPF();
445 apf.changeSign();
446 return getConstantFP(apf);
386447 }
387448
388449
449510 StructType* LLVMContext::getStructType(const std::vector& Params,
450511 bool isPacked) {
451512 return StructType::get(Params, isPacked);
513 }
514
515 StructType *LLVMContext::getStructType(const Type *type, ...) {
516 va_list ap;
517 std::vector StructFields;
518 va_start(ap, type);
519 while (type) {
520 StructFields.push_back(type);
521 type = va_arg(ap, llvm::Type*);
522 }
523 return StructType::get(StructFields);
452524 }
453525
454526 // ArrayType accessors
298298 if (isa(BBTerm->getType()))
299299 BBTerm->replaceAllUsesWith(UndefValue::get(BBTerm->getType()));
300300 else if (BB->getTerminator()->getType() != Type::VoidTy)
301 BBTerm->replaceAllUsesWith(Constant::getNullValue(BBTerm->getType()));
301 BBTerm->replaceAllUsesWith(
302 BD.getContext().getNullValue(BBTerm->getType()));
302303
303304 // Replace the old terminator instruction.
304305 BB->getInstList().pop_back();
7373 if (isa(TheInst->getType()))
7474 TheInst->replaceAllUsesWith(UndefValue::get(TheInst->getType()));
7575 else if (TheInst->getType() != Type::VoidTy)
76 TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));
76 TheInst->replaceAllUsesWith(Context.getNullValue(TheInst->getType()));
7777
7878 // Remove the instruction from the program.
7979 TheInst->getParent()->getInstList().erase(TheInst);
710710 // sbyte* so it matches the signature of the resolver function.
711711
712712 // GetElementPtr *funcName, ulong 0, ulong 0
713 std::vector GEPargs(2,Constant::getNullValue(Type::Int32Ty));
713 std::vector GEPargs(2,
714 BD.getContext().getNullValue(Type::Int32Ty));
714715 Value *GEP = ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
715716 std::vector ResolverArgs;
716717 ResolverArgs.push_back(GEP);
5959 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
6060 if (CallInst *CI = dyn_cast(I)) {
6161 if (!CI->use_empty())
62 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
62 CI->replaceAllUsesWith(Context->getNullValue(CI->getType()));
6363 CI->getParent()->getInstList().erase(CI);
6464 break;
6565 }
188188 if (GlobalVariable* gvn = dyn_cast(op)) {
189189 Constant* cn = gvn->getInitializer();
190190 if (ConstantArray* ca = dyn_cast(cn)) {
191 if ( ca->isCString() ) {
191 if ( ca->isCString(getGlobalContext()) ) {
192192 name = ".objc_class_name_" + ca->getAsString();
193193 return true;
194194 }
7272 GTy,
7373 false, // Not constant.
7474 GlobalValue::InternalLinkage,
75 Constant::getNullValue(GTy),
75 context.getNullValue(GTy),
7676 "myglobal");
7777
7878 // Make a function that points to a global.
283283 public:
284284 int DeletedCalls;
285285 Value *AURWArgument;
286
287 RecoveringVH() : DeletedCalls(0), AURWArgument(NULL) {}
286 LLVMContext *Context;
287
288 RecoveringVH() : DeletedCalls(0), AURWArgument(NULL),
289 Context(&getGlobalContext()) {}
288290 RecoveringVH(Value *V)
289 : CallbackVH(V), DeletedCalls(0), AURWArgument(NULL) {}
291 : CallbackVH(V), DeletedCalls(0), AURWArgument(NULL),
292 Context(&getGlobalContext()) {}
290293
291294 private:
292295 virtual void deleted() {
293 getValPtr()->replaceAllUsesWith(Constant::getNullValue(Type::Int32Ty));
296 getValPtr()->replaceAllUsesWith(Context->getNullValue(Type::Int32Ty));
294297 setValPtr(NULL);
295298 }
296299 virtual void allUsesReplacedWith(Value *new_value) {
306309 RecoveringVH RVH;
307310 RVH = BitcastV.get();
308311 std::auto_ptr BitcastUser(
309 BinaryOperator::CreateAdd(RVH, Constant::getNullValue(Type::Int32Ty)));
312 BinaryOperator::CreateAdd(RVH,
313 getGlobalContext().getNullValue(Type::Int32Ty)));
310314 EXPECT_EQ(BitcastV.get(), BitcastUser->getOperand(0));
311315 BitcastV.reset(); // Would crash without the ValueHandler.
312 EXPECT_EQ(Constant::getNullValue(Type::Int32Ty), RVH.AURWArgument);
313 EXPECT_EQ(Constant::getNullValue(Type::Int32Ty), BitcastUser->getOperand(0));
314 }
315
316 }
316 EXPECT_EQ(getGlobalContext().getNullValue(Type::Int32Ty), RVH.AURWArgument);
317 EXPECT_EQ(getGlobalContext().getNullValue(Type::Int32Ty),
318 BitcastUser->getOperand(0));
319 }
320
321 }