1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "UpgradeInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ParameterAttributes.h"
21 #include "llvm/ValueSymbolTable.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/MathExtras.h"
31 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
32 // relating to upreferences in the input stream.
34 //#define DEBUG_UPREFS 1
36 #define UR_OUT(X) std::cerr << X
41 #define YYERROR_VERBOSE 1
42 #define YYINCLUDED_STDLIB_H
48 int yyerror(const char*);
49 static void warning(const std::string& WarningMsg);
53 std::istream* LexInput;
54 static std::string CurFilename;
56 // This bool controls whether attributes are ever added to function declarations
57 // definitions and calls.
58 static bool AddAttributes = false;
60 static Module *ParserResult;
61 static bool ObsoleteVarArgs;
62 static bool NewVarArgs;
63 static BasicBlock *CurBB;
64 static GlobalVariable *CurGV;
65 static unsigned lastCallingConv;
67 // This contains info used when building the body of a function. It is
68 // destroyed when the function is completed.
70 typedef std::vector<Value *> ValueList; // Numbered defs
72 typedef std::pair<std::string,TypeInfo> RenameMapKey;
73 typedef std::map<RenameMapKey,std::string> RenameMapType;
76 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
77 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
79 static struct PerModuleInfo {
80 Module *CurrentModule;
81 std::map<const Type *, ValueList> Values; // Module level numbered definitions
82 std::map<const Type *,ValueList> LateResolveValues;
83 std::vector<PATypeHolder> Types;
84 std::vector<Signedness> TypeSigns;
85 std::map<std::string,Signedness> NamedTypeSigns;
86 std::map<std::string,Signedness> NamedValueSigns;
87 std::map<ValID, PATypeHolder> LateResolveTypes;
88 static Module::Endianness Endian;
89 static Module::PointerSize PointerSize;
90 RenameMapType RenameMap;
92 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
93 /// how they were referenced and on which line of the input they came from so
94 /// that we can resolve them later and print error messages as appropriate.
95 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
97 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
98 // references to global values. Global values may be referenced before they
99 // are defined, and if so, the temporary object that they represent is held
100 // here. This is used for forward references of GlobalValues.
102 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
104 GlobalRefsType GlobalRefs;
107 // If we could not resolve some functions at function compilation time
108 // (calls to functions before they are defined), resolve them now... Types
109 // are resolved when the constant pool has been completely parsed.
111 ResolveDefinitions(LateResolveValues);
113 // Check to make sure that all global value forward references have been
116 if (!GlobalRefs.empty()) {
117 std::string UndefinedReferences = "Unresolved global references exist:\n";
119 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
121 UndefinedReferences += " " + I->first.first->getDescription() + " " +
122 I->first.second.getName() + "\n";
124 error(UndefinedReferences);
128 if (CurrentModule->getDataLayout().empty()) {
129 std::string dataLayout;
130 if (Endian != Module::AnyEndianness)
131 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
132 if (PointerSize != Module::AnyPointerSize) {
133 if (!dataLayout.empty())
135 dataLayout.append(PointerSize == Module::Pointer64 ?
136 "p:64:64" : "p:32:32");
138 CurrentModule->setDataLayout(dataLayout);
141 Values.clear(); // Clear out function local definitions
144 NamedTypeSigns.clear();
145 NamedValueSigns.clear();
149 // GetForwardRefForGlobal - Check to see if there is a forward reference
150 // for this global. If so, remove it from the GlobalRefs map and return it.
151 // If not, just return null.
152 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
153 // Check to see if there is a forward reference to this global variable...
154 // if there is, eliminate it and patch the reference to use the new def'n.
155 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
156 GlobalValue *Ret = 0;
157 if (I != GlobalRefs.end()) {
163 void setEndianness(Module::Endianness E) { Endian = E; }
164 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
167 Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
168 Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
170 static struct PerFunctionInfo {
171 Function *CurrentFunction; // Pointer to current function being created
173 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
174 std::map<const Type*, ValueList> LateResolveValues;
175 bool isDeclare; // Is this function a forward declararation?
176 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
178 /// BBForwardRefs - When we see forward references to basic blocks, keep
179 /// track of them here.
180 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
181 std::vector<BasicBlock*> NumberedBlocks;
182 RenameMapType RenameMap;
185 inline PerFunctionInfo() {
188 Linkage = GlobalValue::ExternalLinkage;
191 inline void FunctionStart(Function *M) {
196 void FunctionDone() {
197 NumberedBlocks.clear();
199 // Any forward referenced blocks left?
200 if (!BBForwardRefs.empty()) {
201 error("Undefined reference to label " +
202 BBForwardRefs.begin()->first->getName());
206 // Resolve all forward references now.
207 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
209 Values.clear(); // Clear out function local definitions
213 Linkage = GlobalValue::ExternalLinkage;
215 } CurFun; // Info for the current function...
217 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
219 /// This function is just a utility to make a Key value for the rename map.
220 /// The Key is a combination of the name, type, Signedness of the original
221 /// value (global/function). This just constructs the key and ensures that
222 /// named Signedness values are resolved to the actual Signedness.
223 /// @brief Make a key for the RenameMaps
224 static RenameMapKey makeRenameMapKey(const std::string &Name, const Type* Ty,
225 const Signedness &Sign) {
229 // Don't allow Named Signedness nodes because they won't match. The actual
230 // Signedness must be looked up in the NamedTypeSigns map.
231 TI.S.copy(CurModule.NamedTypeSigns[Sign.getName()]);
234 return std::make_pair(Name, TI);
238 //===----------------------------------------------------------------------===//
239 // Code to handle definitions of all the types
240 //===----------------------------------------------------------------------===//
242 static int InsertValue(Value *V,
243 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
244 if (V->hasName()) return -1; // Is this a numbered definition?
246 // Yes, insert the value into the value table...
247 ValueList &List = ValueTab[V->getType()];
249 return List.size()-1;
252 static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
254 case ValID::NumberVal: // Is it a numbered definition?
255 // Module constants occupy the lowest numbered slots...
256 if ((unsigned)D.Num < CurModule.Types.size()) {
257 return CurModule.Types[(unsigned)D.Num];
260 case ValID::NameVal: // Is it a named definition?
261 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
266 error("Internal parser error: Invalid symbol type reference");
270 // If we reached here, we referenced either a symbol that we don't know about
271 // or an id number that hasn't been read yet. We may be referencing something
272 // forward, so just create an entry to be resolved later and get to it...
274 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
276 if (inFunctionScope()) {
277 if (D.Type == ValID::NameVal) {
278 error("Reference to an undefined type: '" + D.getName() + "'");
281 error("Reference to an undefined type: #" + itostr(D.Num));
286 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
287 if (I != CurModule.LateResolveTypes.end())
290 Type *Typ = OpaqueType::get();
291 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
295 /// This is like the getType method except that instead of looking up the type
296 /// for a given ID, it looks up that type's sign.
297 /// @brief Get the signedness of a referenced type
298 static Signedness getTypeSign(const ValID &D) {
300 case ValID::NumberVal: // Is it a numbered definition?
301 // Module constants occupy the lowest numbered slots...
302 if ((unsigned)D.Num < CurModule.TypeSigns.size()) {
303 return CurModule.TypeSigns[(unsigned)D.Num];
306 case ValID::NameVal: { // Is it a named definition?
307 std::map<std::string,Signedness>::const_iterator I =
308 CurModule.NamedTypeSigns.find(D.Name);
309 if (I != CurModule.NamedTypeSigns.end())
311 // Perhaps its a named forward .. just cache the name
319 // If we don't find it, its signless
325 /// This function is analagous to getElementType in LLVM. It provides the same
326 /// function except that it looks up the Signedness instead of the type. This is
327 /// used when processing GEP instructions that need to extract the type of an
328 /// indexed struct/array/ptr member.
329 /// @brief Look up an element's sign.
330 static Signedness getElementSign(const ValueInfo& VI,
331 const std::vector<Value*> &Indices) {
332 const Type *Ptr = VI.V->getType();
333 assert(isa<PointerType>(Ptr) && "Need pointer type");
337 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
338 if (CurIdx == Indices.size())
341 Value *Index = Indices[CurIdx++];
342 assert(!isa<PointerType>(CT) || CurIdx == 1 && "Invalid type");
343 Ptr = CT->getTypeAtIndex(Index);
344 if (const Type* Ty = Ptr->getForwardedType())
346 assert(S.isComposite() && "Bad Signedness type");
347 if (isa<StructType>(CT)) {
348 S = S.get(cast<ConstantInt>(Index)->getZExtValue());
353 S = CurModule.NamedTypeSigns[S.getName()];
356 Result.makeComposite(S);
360 /// This function just translates a ConstantInfo into a ValueInfo and calls
361 /// getElementSign(ValueInfo,...). Its just a convenience.
362 /// @brief ConstantInfo version of getElementSign.
363 static Signedness getElementSign(const ConstInfo& CI,
364 const std::vector<Constant*> &Indices) {
368 std::vector<Value*> Idx;
369 for (unsigned i = 0; i < Indices.size(); ++i)
370 Idx.push_back(Indices[i]);
371 Signedness result = getElementSign(VI, Idx);
376 /// This function determines if two function types differ only in their use of
377 /// the sret parameter attribute in the first argument. If they are identical
378 /// in all other respects, it returns true. Otherwise, it returns false.
379 static bool FuncTysDifferOnlyBySRet(const FunctionType *F1,
380 const FunctionType *F2) {
381 if (F1->getReturnType() != F2->getReturnType() ||
382 F1->getNumParams() != F2->getNumParams())
384 const ParamAttrsList *PAL1 = F1->getParamAttrs();
385 const ParamAttrsList *PAL2 = F2->getParamAttrs();
386 if (PAL1 && !PAL2 || PAL2 && !PAL1)
388 if (PAL1 && PAL2 && ((PAL1->size() != PAL2->size()) ||
389 (PAL1->getParamAttrs(0) != PAL2->getParamAttrs(0))))
391 unsigned SRetMask = ~unsigned(ParamAttr::StructRet);
392 for (unsigned i = 0; i < F1->getNumParams(); ++i) {
393 if (F1->getParamType(i) != F2->getParamType(i) || (PAL1 && PAL2 &&
394 (unsigned(PAL1->getParamAttrs(i+1)) & SRetMask !=
395 unsigned(PAL2->getParamAttrs(i+1)) & SRetMask)))
401 /// This function determines if the type of V and Ty differ only by the SRet
402 /// parameter attribute. This is a more generalized case of
403 /// FuncTysDIfferOnlyBySRet since it doesn't require FunctionType arguments.
404 static bool TypesDifferOnlyBySRet(Value *V, const Type* Ty) {
405 if (V->getType() == Ty)
407 const PointerType *PF1 = dyn_cast<PointerType>(Ty);
408 const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
410 const FunctionType* FT1 = dyn_cast<FunctionType>(PF1->getElementType());
411 const FunctionType* FT2 = dyn_cast<FunctionType>(PF2->getElementType());
413 return FuncTysDifferOnlyBySRet(FT1, FT2);
418 // The upgrade of csretcc to sret param attribute may have caused a function
419 // to not be found because the param attribute changed the type of the called
420 // function. This helper function, used in getExistingValue, detects that
421 // situation and bitcasts the function to the correct type.
422 static Value* handleSRetFuncTypeMerge(Value *V, const Type* Ty) {
423 // Handle degenerate cases
426 if (V->getType() == Ty)
429 const PointerType *PF1 = dyn_cast<PointerType>(Ty);
430 const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
432 const FunctionType *FT1 = dyn_cast<FunctionType>(PF1->getElementType());
433 const FunctionType *FT2 = dyn_cast<FunctionType>(PF2->getElementType());
434 if (FT1 && FT2 && FuncTysDifferOnlyBySRet(FT1, FT2)) {
435 const ParamAttrsList *PAL2 = FT2->getParamAttrs();
436 if (PAL2 && PAL2->paramHasAttr(1, ParamAttr::StructRet))
438 else if (Constant *C = dyn_cast<Constant>(V))
439 return ConstantExpr::getBitCast(C, PF1);
441 return new BitCastInst(V, PF1, "upgrd.cast", CurBB);
448 // getExistingValue - Look up the value specified by the provided type and
449 // the provided ValID. If the value exists and has already been defined, return
450 // it. Otherwise return null.
452 static Value *getExistingValue(const Type *Ty, const ValID &D) {
453 if (isa<FunctionType>(Ty)) {
454 error("Functions are not values and must be referenced as pointers");
458 case ValID::NumberVal: { // Is it a numbered definition?
459 unsigned Num = (unsigned)D.Num;
461 // Module constants occupy the lowest numbered slots...
462 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
463 if (VI != CurModule.Values.end()) {
464 if (Num < VI->second.size())
465 return VI->second[Num];
466 Num -= VI->second.size();
469 // Make sure that our type is within bounds
470 VI = CurFun.Values.find(Ty);
471 if (VI == CurFun.Values.end()) return 0;
473 // Check that the number is within bounds...
474 if (VI->second.size() <= Num) return 0;
476 return VI->second[Num];
479 case ValID::NameVal: { // Is it a named definition?
480 // Get the name out of the ID
481 RenameMapKey Key = makeRenameMapKey(D.Name, Ty, D.S);
483 if (inFunctionScope()) {
484 // See if the name was renamed
485 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
486 std::string LookupName;
487 if (I != CurFun.RenameMap.end())
488 LookupName = I->second;
491 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
492 V = SymTab.lookup(LookupName);
493 if (V && V->getType() != Ty)
494 V = handleSRetFuncTypeMerge(V, Ty);
495 assert((!V || TypesDifferOnlyBySRet(V, Ty)) && "Found wrong type");
498 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
499 std::string LookupName;
500 if (I != CurModule.RenameMap.end())
501 LookupName = I->second;
504 V = CurModule.CurrentModule->getValueSymbolTable().lookup(LookupName);
505 if (V && V->getType() != Ty)
506 V = handleSRetFuncTypeMerge(V, Ty);
507 assert((!V || TypesDifferOnlyBySRet(V, Ty)) && "Found wrong type");
512 D.destroy(); // Free old strdup'd memory...
516 // Check to make sure that "Ty" is an integral type, and that our
517 // value will fit into the specified type...
518 case ValID::ConstSIntVal: // Is it a constant pool reference??
519 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
520 error("Signed integral constant '" + itostr(D.ConstPool64) +
521 "' is invalid for type '" + Ty->getDescription() + "'");
523 return ConstantInt::get(Ty, D.ConstPool64);
525 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
526 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
527 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
528 error("Integral constant '" + utostr(D.UConstPool64) +
529 "' is invalid or out of range");
530 else // This is really a signed reference. Transmogrify.
531 return ConstantInt::get(Ty, D.ConstPool64);
533 return ConstantInt::get(Ty, D.UConstPool64);
535 case ValID::ConstFPVal: // Is it a floating point const pool reference?
536 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
537 error("FP constant invalid for type");
538 return ConstantFP::get(Ty, D.ConstPoolFP);
540 case ValID::ConstNullVal: // Is it a null value?
541 if (!isa<PointerType>(Ty))
542 error("Cannot create a a non pointer null");
543 return ConstantPointerNull::get(cast<PointerType>(Ty));
545 case ValID::ConstUndefVal: // Is it an undef value?
546 return UndefValue::get(Ty);
548 case ValID::ConstZeroVal: // Is it a zero value?
549 return Constant::getNullValue(Ty);
551 case ValID::ConstantVal: // Fully resolved constant?
552 if (D.ConstantValue->getType() != Ty)
553 error("Constant expression type different from required type");
554 return D.ConstantValue;
556 case ValID::InlineAsmVal: { // Inline asm expression
557 const PointerType *PTy = dyn_cast<PointerType>(Ty);
558 const FunctionType *FTy =
559 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
560 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
561 error("Invalid type for asm constraint string");
562 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
563 D.IAD->HasSideEffects);
564 D.destroy(); // Free InlineAsmDescriptor.
568 assert(0 && "Unhandled case");
572 assert(0 && "Unhandled case");
576 // getVal - This function is identical to getExistingValue, except that if a
577 // value is not already defined, it "improvises" by creating a placeholder var
578 // that looks and acts just like the requested variable. When the value is
579 // defined later, all uses of the placeholder variable are replaced with the
582 static Value *getVal(const Type *Ty, const ValID &ID) {
583 if (Ty == Type::LabelTy)
584 error("Cannot use a basic block here");
586 // See if the value has already been defined.
587 Value *V = getExistingValue(Ty, ID);
590 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
591 error("Invalid use of a composite type");
593 // If we reached here, we referenced either a symbol that we don't know about
594 // or an id number that hasn't been read yet. We may be referencing something
595 // forward, so just create an entry to be resolved later and get to it...
596 V = new Argument(Ty);
598 // Remember where this forward reference came from. FIXME, shouldn't we try
599 // to recycle these things??
600 CurModule.PlaceHolderInfo.insert(
601 std::make_pair(V, std::make_pair(ID, Upgradelineno)));
603 if (inFunctionScope())
604 InsertValue(V, CurFun.LateResolveValues);
606 InsertValue(V, CurModule.LateResolveValues);
610 /// @brief This just makes any name given to it unique, up to MAX_UINT times.
611 static std::string makeNameUnique(const std::string& Name) {
612 static unsigned UniqueNameCounter = 1;
613 std::string Result(Name);
614 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
618 /// getBBVal - This is used for two purposes:
619 /// * If isDefinition is true, a new basic block with the specified ID is being
621 /// * If isDefinition is true, this is a reference to a basic block, which may
622 /// or may not be a forward reference.
624 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
625 assert(inFunctionScope() && "Can't get basic block at global scope");
631 error("Illegal label reference " + ID.getName());
633 case ValID::NumberVal: // Is it a numbered definition?
634 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
635 CurFun.NumberedBlocks.resize(ID.Num+1);
636 BB = CurFun.NumberedBlocks[ID.Num];
638 case ValID::NameVal: // Is it a named definition?
640 if (Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name)) {
641 if (N->getType() != Type::LabelTy) {
642 // Register names didn't use to conflict with basic block names
643 // because of type planes. Now they all have to be unique. So, we just
644 // rename the register and treat this name as if no basic block
646 RenameMapKey Key = makeRenameMapKey(ID.Name, N->getType(), ID.S);
647 N->setName(makeNameUnique(N->getName()));
648 CurModule.RenameMap[Key] = N->getName();
651 BB = cast<BasicBlock>(N);
657 // See if the block has already been defined.
659 // If this is the definition of the block, make sure the existing value was
660 // just a forward reference. If it was a forward reference, there will be
661 // an entry for it in the PlaceHolderInfo map.
662 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
663 // The existing value was a definition, not a forward reference.
664 error("Redefinition of label " + ID.getName());
666 ID.destroy(); // Free strdup'd memory.
670 // Otherwise this block has not been seen before.
671 BB = new BasicBlock("", CurFun.CurrentFunction);
672 if (ID.Type == ValID::NameVal) {
673 BB->setName(ID.Name);
675 CurFun.NumberedBlocks[ID.Num] = BB;
678 // If this is not a definition, keep track of it so we can use it as a forward
681 // Remember where this forward reference came from.
682 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
684 // The forward declaration could have been inserted anywhere in the
685 // function: insert it into the correct place now.
686 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
687 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
694 //===----------------------------------------------------------------------===//
695 // Code to handle forward references in instructions
696 //===----------------------------------------------------------------------===//
698 // This code handles the late binding needed with statements that reference
699 // values not defined yet... for example, a forward branch, or the PHI node for
702 // This keeps a table (CurFun.LateResolveValues) of all such forward references
703 // and back patchs after we are done.
706 // ResolveDefinitions - If we could not resolve some defs at parsing
707 // time (forward branches, phi functions for loops, etc...) resolve the
711 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
712 std::map<const Type*,ValueList> *FutureLateResolvers) {
714 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
715 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
716 E = LateResolvers.end(); LRI != E; ++LRI) {
717 const Type* Ty = LRI->first;
718 ValueList &List = LRI->second;
719 while (!List.empty()) {
720 Value *V = List.back();
723 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
724 CurModule.PlaceHolderInfo.find(V);
725 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
727 ValID &DID = PHI->second.first;
729 Value *TheRealValue = getExistingValue(Ty, DID);
731 V->replaceAllUsesWith(TheRealValue);
733 CurModule.PlaceHolderInfo.erase(PHI);
734 } else if (FutureLateResolvers) {
735 // Functions have their unresolved items forwarded to the module late
737 InsertValue(V, *FutureLateResolvers);
739 if (DID.Type == ValID::NameVal) {
740 error("Reference to an invalid definition: '" + DID.getName() +
741 "' of type '" + V->getType()->getDescription() + "'",
745 error("Reference to an invalid definition: #" +
746 itostr(DID.Num) + " of type '" +
747 V->getType()->getDescription() + "'", PHI->second.second);
754 LateResolvers.clear();
757 /// This function is used for type resolution and upref handling. When a type
758 /// becomes concrete, this function is called to adjust the signedness for the
760 static void ResolveTypeSign(const Type* oldTy, const Signedness &Sign) {
761 std::string TyName = CurModule.CurrentModule->getTypeName(oldTy);
763 CurModule.NamedTypeSigns[TyName] = Sign;
766 /// ResolveTypeTo - A brand new type was just declared. This means that (if
767 /// name is not null) things referencing Name can be resolved. Otherwise,
768 /// things refering to the number can be resolved. Do this now.
769 static void ResolveTypeTo(char *Name, const Type *ToTy, const Signedness& Sign){
772 D = ValID::create(Name);
774 D = ValID::create((int)CurModule.Types.size());
778 CurModule.NamedTypeSigns[Name] = Sign;
780 std::map<ValID, PATypeHolder>::iterator I =
781 CurModule.LateResolveTypes.find(D);
782 if (I != CurModule.LateResolveTypes.end()) {
783 const Type *OldTy = I->second.get();
784 ((DerivedType*)OldTy)->refineAbstractTypeTo(ToTy);
785 CurModule.LateResolveTypes.erase(I);
789 /// This is the implementation portion of TypeHasInteger. It traverses the
790 /// type given, avoiding recursive types, and returns true as soon as it finds
791 /// an integer type. If no integer type is found, it returns false.
792 static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
793 // Handle some easy cases
794 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
798 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
799 return STy->getElementType()->isInteger();
801 // Avoid type structure recursion
802 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
807 // Push us on the type stack
810 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
811 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
813 FunctionType::param_iterator I = FTy->param_begin();
814 FunctionType::param_iterator E = FTy->param_end();
816 if (TypeHasIntegerI(*I, Stack))
819 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
820 StructType::element_iterator I = STy->element_begin();
821 StructType::element_iterator E = STy->element_end();
822 for (; I != E; ++I) {
823 if (TypeHasIntegerI(*I, Stack))
828 // There shouldn't be anything else, but its definitely not integer
829 assert(0 && "What type is this?");
833 /// This is the interface to TypeHasIntegerI. It just provides the type stack,
834 /// to avoid recursion, and then calls TypeHasIntegerI.
835 static inline bool TypeHasInteger(const Type *Ty) {
836 std::vector<const Type*> TyStack;
837 return TypeHasIntegerI(Ty, TyStack);
840 // setValueName - Set the specified value to the name given. The name may be
841 // null potentially, in which case this is a noop. The string passed in is
842 // assumed to be a malloc'd string buffer, and is free'd by this function.
844 static void setValueName(const ValueInfo &V, char *NameStr) {
846 std::string Name(NameStr); // Copy string
847 free(NameStr); // Free old string
849 if (V.V->getType() == Type::VoidTy) {
850 error("Can't assign name '" + Name + "' to value with void type");
854 assert(inFunctionScope() && "Must be in function scope");
856 // Search the function's symbol table for an existing value of this name
857 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
858 Value* Existing = ST.lookup(Name);
860 // An existing value of the same name was found. This might have happened
861 // because of the integer type planes collapsing in LLVM 2.0.
862 if (Existing->getType() == V.V->getType() &&
863 !TypeHasInteger(Existing->getType())) {
864 // If the type does not contain any integers in them then this can't be
865 // a type plane collapsing issue. It truly is a redefinition and we
866 // should error out as the assembly is invalid.
867 error("Redefinition of value named '" + Name + "' of type '" +
868 V.V->getType()->getDescription() + "'");
871 // In LLVM 2.0 we don't allow names to be re-used for any values in a
872 // function, regardless of Type. Previously re-use of names was okay as
873 // long as they were distinct types. With type planes collapsing because
874 // of the signedness change and because of PR411, this can no longer be
875 // supported. We must search the entire symbol table for a conflicting
876 // name and make the name unique. No warning is needed as this can't
878 std::string NewName = makeNameUnique(Name);
879 // We're changing the name but it will probably be used by other
880 // instructions as operands later on. Consequently we have to retain
881 // a mapping of the renaming that we're doing.
882 RenameMapKey Key = makeRenameMapKey(Name, V.V->getType(), V.S);
883 CurFun.RenameMap[Key] = NewName;
892 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
893 /// this is a declaration, otherwise it is a definition.
894 static GlobalVariable *
895 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
896 bool isConstantGlobal, const Type *Ty,
897 Constant *Initializer,
898 const Signedness &Sign) {
899 if (isa<FunctionType>(Ty))
900 error("Cannot declare global vars of function type");
902 const PointerType *PTy = PointerType::get(Ty);
906 Name = NameStr; // Copy string
907 free(NameStr); // Free old string
910 // See if this global value was forward referenced. If so, recycle the
914 ID = ValID::create((char*)Name.c_str());
916 ID = ValID::create((int)CurModule.Values[PTy].size());
918 ID.S.makeComposite(Sign);
920 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
921 // Move the global to the end of the list, from whereever it was
922 // previously inserted.
923 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
924 CurModule.CurrentModule->getGlobalList().remove(GV);
925 CurModule.CurrentModule->getGlobalList().push_back(GV);
926 GV->setInitializer(Initializer);
927 GV->setLinkage(Linkage);
928 GV->setConstant(isConstantGlobal);
929 InsertValue(GV, CurModule.Values);
933 // If this global has a name, check to see if there is already a definition
934 // of this global in the module and emit warnings if there are conflicts.
936 // The global has a name. See if there's an existing one of the same name.
937 if (CurModule.CurrentModule->getNamedGlobal(Name) ||
938 CurModule.CurrentModule->getFunction(Name)) {
939 // We found an existing global of the same name. This isn't allowed
940 // in LLVM 2.0. Consequently, we must alter the name of the global so it
941 // can at least compile. This can happen because of type planes
942 // There is alread a global of the same name which means there is a
943 // conflict. Let's see what we can do about it.
944 std::string NewName(makeNameUnique(Name));
945 if (Linkage != GlobalValue::InternalLinkage) {
946 // The linkage of this gval is external so we can't reliably rename
947 // it because it could potentially create a linking problem.
948 // However, we can't leave the name conflict in the output either or
949 // it won't assemble with LLVM 2.0. So, all we can do is rename
950 // this one to something unique and emit a warning about the problem.
951 warning("Renaming global variable '" + Name + "' to '" + NewName +
952 "' may cause linkage errors");
955 // Put the renaming in the global rename map
956 RenameMapKey Key = makeRenameMapKey(Name, PointerType::get(Ty), ID.S);
957 CurModule.RenameMap[Key] = NewName;
964 // Otherwise there is no existing GV to use, create one now.
966 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
967 CurModule.CurrentModule);
968 InsertValue(GV, CurModule.Values);
969 // Remember the sign of this global.
970 CurModule.NamedValueSigns[Name] = ID.S;
974 // setTypeName - Set the specified type to the name given. The name may be
975 // null potentially, in which case this is a noop. The string passed in is
976 // assumed to be a malloc'd string buffer, and is freed by this function.
978 // This function returns true if the type has already been defined, but is
979 // allowed to be redefined in the specified context. If the name is a new name
980 // for the type plane, it is inserted and false is returned.
981 static bool setTypeName(const PATypeInfo& TI, char *NameStr) {
982 assert(!inFunctionScope() && "Can't give types function-local names");
983 if (NameStr == 0) return false;
985 std::string Name(NameStr); // Copy string
986 free(NameStr); // Free old string
988 const Type* Ty = TI.PAT->get();
990 // We don't allow assigning names to void type
991 if (Ty == Type::VoidTy) {
992 error("Can't assign name '" + Name + "' to the void type");
996 // Set the type name, checking for conflicts as we do so.
997 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, Ty);
999 // Save the sign information for later use
1000 CurModule.NamedTypeSigns[Name] = TI.S;
1002 if (AlreadyExists) { // Inserting a name that is already defined???
1003 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
1004 assert(Existing && "Conflict but no matching type?");
1006 // There is only one case where this is allowed: when we are refining an
1007 // opaque type. In this case, Existing will be an opaque type.
1008 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
1009 // We ARE replacing an opaque type!
1010 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(Ty);
1014 // Otherwise, this is an attempt to redefine a type. That's okay if
1015 // the redefinition is identical to the original. This will be so if
1016 // Existing and T point to the same Type object. In this one case we
1017 // allow the equivalent redefinition.
1018 if (Existing == Ty) return true; // Yes, it's equal.
1020 // Any other kind of (non-equivalent) redefinition is an error.
1021 error("Redefinition of type named '" + Name + "' in the '" +
1022 Ty->getDescription() + "' type plane");
1028 //===----------------------------------------------------------------------===//
1029 // Code for handling upreferences in type names...
1032 // TypeContains - Returns true if Ty directly contains E in it.
1034 static bool TypeContains(const Type *Ty, const Type *E) {
1035 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
1036 E) != Ty->subtype_end();
1040 struct UpRefRecord {
1041 // NestingLevel - The number of nesting levels that need to be popped before
1042 // this type is resolved.
1043 unsigned NestingLevel;
1045 // LastContainedTy - This is the type at the current binding level for the
1046 // type. Every time we reduce the nesting level, this gets updated.
1047 const Type *LastContainedTy;
1049 // UpRefTy - This is the actual opaque type that the upreference is
1050 // represented with.
1051 OpaqueType *UpRefTy;
1053 UpRefRecord(unsigned NL, OpaqueType *URTy)
1054 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) { }
1058 // UpRefs - A list of the outstanding upreferences that need to be resolved.
1059 static std::vector<UpRefRecord> UpRefs;
1061 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1062 /// called. It loops through the UpRefs vector, which is a list of the
1063 /// currently active types. For each type, if the up reference is contained in
1064 /// the newly completed type, we decrement the level count. When the level
1065 /// count reaches zero, the upreferenced type is the type that is passed in:
1066 /// thus we can complete the cycle.
1068 static PATypeHolder HandleUpRefs(const Type *ty, const Signedness& Sign) {
1069 // If Ty isn't abstract, or if there are no up-references in it, then there is
1070 // nothing to resolve here.
1071 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1073 PATypeHolder Ty(ty);
1074 UR_OUT("Type '" << Ty->getDescription() <<
1075 "' newly formed. Resolving upreferences.\n" <<
1076 UpRefs.size() << " upreferences active!\n");
1078 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1079 // to zero), we resolve them all together before we resolve them to Ty. At
1080 // the end of the loop, if there is anything to resolve to Ty, it will be in
1082 OpaqueType *TypeToResolve = 0;
1085 for (; i != UpRefs.size(); ++i) {
1086 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1087 << UpRefs[i].UpRefTy->getDescription() << ") = "
1088 << (TypeContains(Ty, UpRefs[i].UpRefTy) ? "true" : "false") << "\n");
1089 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
1090 // Decrement level of upreference
1091 unsigned Level = --UpRefs[i].NestingLevel;
1092 UpRefs[i].LastContainedTy = Ty;
1093 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
1094 if (Level == 0) { // Upreference should be resolved!
1095 if (!TypeToResolve) {
1096 TypeToResolve = UpRefs[i].UpRefTy;
1098 UR_OUT(" * Resolving upreference for "
1099 << UpRefs[i].UpRefTy->getDescription() << "\n";
1100 std::string OldName = UpRefs[i].UpRefTy->getDescription());
1101 ResolveTypeSign(UpRefs[i].UpRefTy, Sign);
1102 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1103 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
1104 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
1106 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
1107 --i; // Do not skip the next element...
1112 if (TypeToResolve) {
1113 UR_OUT(" * Resolving upreference for "
1114 << UpRefs[i].UpRefTy->getDescription() << "\n";
1115 std::string OldName = TypeToResolve->getDescription());
1116 ResolveTypeSign(TypeToResolve, Sign);
1117 TypeToResolve->refineAbstractTypeTo(Ty);
1123 bool Signedness::operator<(const Signedness &that) const {
1126 return *(this->name) < *(that.name);
1128 return CurModule.NamedTypeSigns[*name] < that;
1129 } else if (that.isNamed()) {
1130 return *this < CurModule.NamedTypeSigns[*that.name];
1133 if (isComposite() && that.isComposite()) {
1134 if (sv->size() == that.sv->size()) {
1135 SignVector::const_iterator thisI = sv->begin(), thisE = sv->end();
1136 SignVector::const_iterator thatI = that.sv->begin(),
1137 thatE = that.sv->end();
1138 for (; thisI != thisE; ++thisI, ++thatI) {
1139 if (*thisI < *thatI)
1141 else if (!(*thisI == *thatI))
1146 return sv->size() < that.sv->size();
1148 return kind < that.kind;
1151 bool Signedness::operator==(const Signedness &that) const {
1154 return *(this->name) == *(that.name);
1156 return CurModule.NamedTypeSigns[*(this->name)] == that;
1157 else if (that.isNamed())
1158 return *this == CurModule.NamedTypeSigns[*(that.name)];
1159 if (isComposite() && that.isComposite()) {
1160 if (sv->size() == that.sv->size()) {
1161 SignVector::const_iterator thisI = sv->begin(), thisE = sv->end();
1162 SignVector::const_iterator thatI = that.sv->begin(),
1163 thatE = that.sv->end();
1164 for (; thisI != thisE; ++thisI, ++thatI) {
1165 if (!(*thisI == *thatI))
1172 return kind == that.kind;
1175 void Signedness::copy(const Signedness &that) {
1176 if (that.isNamed()) {
1178 name = new std::string(*that.name);
1179 } else if (that.isComposite()) {
1181 sv = new SignVector();
1189 void Signedness::destroy() {
1192 } else if (isComposite()) {
1198 void Signedness::dump() const {
1199 if (isComposite()) {
1200 if (sv->size() == 1) {
1205 for (unsigned i = 0; i < sv->size(); ++i) {
1212 } else if (isNamed()) {
1214 } else if (isSigned()) {
1216 } else if (isUnsigned()) {
1223 static inline Instruction::TermOps
1224 getTermOp(TermOps op) {
1226 default : assert(0 && "Invalid OldTermOp");
1227 case RetOp : return Instruction::Ret;
1228 case BrOp : return Instruction::Br;
1229 case SwitchOp : return Instruction::Switch;
1230 case InvokeOp : return Instruction::Invoke;
1231 case UnwindOp : return Instruction::Unwind;
1232 case UnreachableOp: return Instruction::Unreachable;
1236 static inline Instruction::BinaryOps
1237 getBinaryOp(BinaryOps op, const Type *Ty, const Signedness& Sign) {
1239 default : assert(0 && "Invalid OldBinaryOps");
1245 case SetGT : assert(0 && "Should use getCompareOp");
1246 case AddOp : return Instruction::Add;
1247 case SubOp : return Instruction::Sub;
1248 case MulOp : return Instruction::Mul;
1250 // This is an obsolete instruction so we must upgrade it based on the
1251 // types of its operands.
1252 bool isFP = Ty->isFloatingPoint();
1253 if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1254 // If its a vector type we want to use the element type
1255 isFP = PTy->getElementType()->isFloatingPoint();
1257 return Instruction::FDiv;
1258 else if (Sign.isSigned())
1259 return Instruction::SDiv;
1260 return Instruction::UDiv;
1262 case UDivOp : return Instruction::UDiv;
1263 case SDivOp : return Instruction::SDiv;
1264 case FDivOp : return Instruction::FDiv;
1266 // This is an obsolete instruction so we must upgrade it based on the
1267 // types of its operands.
1268 bool isFP = Ty->isFloatingPoint();
1269 if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1270 // If its a vector type we want to use the element type
1271 isFP = PTy->getElementType()->isFloatingPoint();
1272 // Select correct opcode
1274 return Instruction::FRem;
1275 else if (Sign.isSigned())
1276 return Instruction::SRem;
1277 return Instruction::URem;
1279 case URemOp : return Instruction::URem;
1280 case SRemOp : return Instruction::SRem;
1281 case FRemOp : return Instruction::FRem;
1282 case LShrOp : return Instruction::LShr;
1283 case AShrOp : return Instruction::AShr;
1284 case ShlOp : return Instruction::Shl;
1286 if (Sign.isSigned())
1287 return Instruction::AShr;
1288 return Instruction::LShr;
1289 case AndOp : return Instruction::And;
1290 case OrOp : return Instruction::Or;
1291 case XorOp : return Instruction::Xor;
1295 static inline Instruction::OtherOps
1296 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1297 const Signedness &Sign) {
1298 bool isSigned = Sign.isSigned();
1299 bool isFP = Ty->isFloatingPoint();
1301 default : assert(0 && "Invalid OldSetCC");
1304 predicate = FCmpInst::FCMP_OEQ;
1305 return Instruction::FCmp;
1307 predicate = ICmpInst::ICMP_EQ;
1308 return Instruction::ICmp;
1312 predicate = FCmpInst::FCMP_UNE;
1313 return Instruction::FCmp;
1315 predicate = ICmpInst::ICMP_NE;
1316 return Instruction::ICmp;
1320 predicate = FCmpInst::FCMP_OLE;
1321 return Instruction::FCmp;
1324 predicate = ICmpInst::ICMP_SLE;
1326 predicate = ICmpInst::ICMP_ULE;
1327 return Instruction::ICmp;
1331 predicate = FCmpInst::FCMP_OGE;
1332 return Instruction::FCmp;
1335 predicate = ICmpInst::ICMP_SGE;
1337 predicate = ICmpInst::ICMP_UGE;
1338 return Instruction::ICmp;
1342 predicate = FCmpInst::FCMP_OLT;
1343 return Instruction::FCmp;
1346 predicate = ICmpInst::ICMP_SLT;
1348 predicate = ICmpInst::ICMP_ULT;
1349 return Instruction::ICmp;
1353 predicate = FCmpInst::FCMP_OGT;
1354 return Instruction::FCmp;
1357 predicate = ICmpInst::ICMP_SGT;
1359 predicate = ICmpInst::ICMP_UGT;
1360 return Instruction::ICmp;
1365 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1367 default : assert(0 && "Invalid OldMemoryOps");
1368 case MallocOp : return Instruction::Malloc;
1369 case FreeOp : return Instruction::Free;
1370 case AllocaOp : return Instruction::Alloca;
1371 case LoadOp : return Instruction::Load;
1372 case StoreOp : return Instruction::Store;
1373 case GetElementPtrOp : return Instruction::GetElementPtr;
1377 static inline Instruction::OtherOps
1378 getOtherOp(OtherOps op, const Signedness &Sign) {
1380 default : assert(0 && "Invalid OldOtherOps");
1381 case PHIOp : return Instruction::PHI;
1382 case CallOp : return Instruction::Call;
1383 case SelectOp : return Instruction::Select;
1384 case UserOp1 : return Instruction::UserOp1;
1385 case UserOp2 : return Instruction::UserOp2;
1386 case VAArg : return Instruction::VAArg;
1387 case ExtractElementOp : return Instruction::ExtractElement;
1388 case InsertElementOp : return Instruction::InsertElement;
1389 case ShuffleVectorOp : return Instruction::ShuffleVector;
1390 case ICmpOp : return Instruction::ICmp;
1391 case FCmpOp : return Instruction::FCmp;
1395 static inline Value*
1396 getCast(CastOps op, Value *Src, const Signedness &SrcSign, const Type *DstTy,
1397 const Signedness &DstSign, bool ForceInstruction = false) {
1398 Instruction::CastOps Opcode;
1399 const Type* SrcTy = Src->getType();
1401 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1402 // fp -> ptr cast is no longer supported but we must upgrade this
1403 // by doing a double cast: fp -> int -> ptr
1404 SrcTy = Type::Int64Ty;
1405 Opcode = Instruction::IntToPtr;
1406 if (isa<Constant>(Src)) {
1407 Src = ConstantExpr::getCast(Instruction::FPToUI,
1408 cast<Constant>(Src), SrcTy);
1410 std::string NewName(makeNameUnique(Src->getName()));
1411 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1413 } else if (isa<IntegerType>(DstTy) &&
1414 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1415 // cast type %x to bool was previously defined as setne type %x, null
1416 // The cast semantic is now to truncate, not compare so we must retain
1417 // the original intent by replacing the cast with a setne
1418 Constant* Null = Constant::getNullValue(SrcTy);
1419 Instruction::OtherOps Opcode = Instruction::ICmp;
1420 unsigned short predicate = ICmpInst::ICMP_NE;
1421 if (SrcTy->isFloatingPoint()) {
1422 Opcode = Instruction::FCmp;
1423 predicate = FCmpInst::FCMP_ONE;
1424 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1425 error("Invalid cast to bool");
1427 if (isa<Constant>(Src) && !ForceInstruction)
1428 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1430 return CmpInst::create(Opcode, predicate, Src, Null);
1432 // Determine the opcode to use by calling CastInst::getCastOpcode
1434 CastInst::getCastOpcode(Src, SrcSign.isSigned(), DstTy,
1435 DstSign.isSigned());
1437 } else switch (op) {
1438 default: assert(0 && "Invalid cast token");
1439 case TruncOp: Opcode = Instruction::Trunc; break;
1440 case ZExtOp: Opcode = Instruction::ZExt; break;
1441 case SExtOp: Opcode = Instruction::SExt; break;
1442 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1443 case FPExtOp: Opcode = Instruction::FPExt; break;
1444 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1445 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1446 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1447 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1448 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1449 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1450 case BitCastOp: Opcode = Instruction::BitCast; break;
1453 if (isa<Constant>(Src) && !ForceInstruction)
1454 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1455 return CastInst::create(Opcode, Src, DstTy);
1458 static Instruction *
1459 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1460 std::vector<Value*>& Args) {
1462 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1463 if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' ||
1464 Name[2] != 'v' || Name[3] != 'm' || Name[4] != '.')
1469 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1470 if (Args.size() != 2)
1471 error("Invalid prototype for " + Name);
1472 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1476 if (Name.length() == 14 && !memcmp(&Name[5], "bswap.i", 7)) {
1477 const Type* ArgTy = Args[0]->getType();
1478 Name += ".i" + utostr(cast<IntegerType>(ArgTy)->getBitWidth());
1479 Function *F = cast<Function>(
1480 CurModule.CurrentModule->getOrInsertFunction(Name, RetTy, ArgTy,
1482 return new CallInst(F, Args[0]);
1486 if ((Name.length() <= 14 && !memcmp(&Name[5], "ctpop.i", 7)) ||
1487 (Name.length() <= 13 && !memcmp(&Name[5], "ctlz.i", 6)) ||
1488 (Name.length() <= 13 && !memcmp(&Name[5], "cttz.i", 6))) {
1489 // These intrinsics changed their result type.
1490 const Type* ArgTy = Args[0]->getType();
1491 Function *OldF = CurModule.CurrentModule->getFunction(Name);
1493 OldF->setName("upgrd.rm." + Name);
1495 Function *NewF = cast<Function>(
1496 CurModule.CurrentModule->getOrInsertFunction(Name, Type::Int32Ty,
1499 Instruction *Call = new CallInst(NewF, Args[0], "", CurBB);
1500 return CastInst::createIntegerCast(Call, RetTy, false);
1505 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1506 std::vector<const Type*> Params;
1507 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1508 if (Args.size() != 1)
1509 error("Invalid prototype for " + Name + " prototype");
1510 Params.push_back(PtrTy);
1511 const FunctionType *FTy =
1512 FunctionType::get(Type::VoidTy, Params, false);
1513 const PointerType *PFTy = PointerType::get(FTy);
1514 Value* Func = getVal(PFTy, ID);
1515 Args[0] = new BitCastInst(Args[0], PtrTy, makeNameUnique("va"), CurBB);
1516 return new CallInst(Func, Args.begin(), Args.end());
1517 } else if (Name == "llvm.va_copy") {
1518 if (Args.size() != 2)
1519 error("Invalid prototype for " + Name + " prototype");
1520 Params.push_back(PtrTy);
1521 Params.push_back(PtrTy);
1522 const FunctionType *FTy =
1523 FunctionType::get(Type::VoidTy, Params, false);
1524 const PointerType *PFTy = PointerType::get(FTy);
1525 Value* Func = getVal(PFTy, ID);
1526 std::string InstName0(makeNameUnique("va0"));
1527 std::string InstName1(makeNameUnique("va1"));
1528 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1529 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1530 return new CallInst(Func, Args.begin(), Args.end());
1537 const Type* upgradeGEPCEIndices(const Type* PTy,
1538 std::vector<ValueInfo> *Indices,
1539 std::vector<Constant*> &Result) {
1540 const Type *Ty = PTy;
1542 for (unsigned i = 0, e = Indices->size(); i != e ; ++i) {
1543 Constant *Index = cast<Constant>((*Indices)[i].V);
1545 if (ConstantInt *CI = dyn_cast<ConstantInt>(Index)) {
1546 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1547 // struct indices to i32 struct indices with ZExt for compatibility.
1548 if (CI->getBitWidth() < 32)
1549 Index = ConstantExpr::getCast(Instruction::ZExt, CI, Type::Int32Ty);
1552 if (isa<SequentialType>(Ty)) {
1553 // Make sure that unsigned SequentialType indices are zext'd to
1554 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1555 // all indices for SequentialType elements. We must retain the same
1556 // semantic (zext) for unsigned types.
1557 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType())) {
1558 if (Ity->getBitWidth() < 64 && (*Indices)[i].S.isUnsigned()) {
1559 Index = ConstantExpr::getCast(Instruction::ZExt, Index,Type::Int64Ty);
1563 Result.push_back(Index);
1564 Ty = GetElementPtrInst::getIndexedType(PTy, (Value**)&Result[0],
1565 Result.size(),true);
1567 error("Index list invalid for constant getelementptr");
1572 const Type* upgradeGEPInstIndices(const Type* PTy,
1573 std::vector<ValueInfo> *Indices,
1574 std::vector<Value*> &Result) {
1575 const Type *Ty = PTy;
1577 for (unsigned i = 0, e = Indices->size(); i != e ; ++i) {
1578 Value *Index = (*Indices)[i].V;
1580 if (ConstantInt *CI = dyn_cast<ConstantInt>(Index)) {
1581 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1582 // struct indices to i32 struct indices with ZExt for compatibility.
1583 if (CI->getBitWidth() < 32)
1584 Index = ConstantExpr::getCast(Instruction::ZExt, CI, Type::Int32Ty);
1588 if (isa<StructType>(Ty)) { // Only change struct indices
1589 if (!isa<Constant>(Index)) {
1590 error("Invalid non-constant structure index");
1594 // Make sure that unsigned SequentialType indices are zext'd to
1595 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1596 // all indices for SequentialType elements. We must retain the same
1597 // semantic (zext) for unsigned types.
1598 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType())) {
1599 if (Ity->getBitWidth() < 64 && (*Indices)[i].S.isUnsigned()) {
1600 if (isa<Constant>(Index))
1601 Index = ConstantExpr::getCast(Instruction::ZExt,
1602 cast<Constant>(Index), Type::Int64Ty);
1604 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1605 makeNameUnique("gep"), CurBB);
1609 Result.push_back(Index);
1610 Ty = GetElementPtrInst::getIndexedType(PTy, &Result[0], Result.size(),true);
1612 error("Index list invalid for constant getelementptr");
1617 unsigned upgradeCallingConv(unsigned CC) {
1619 case OldCallingConv::C : return CallingConv::C;
1620 case OldCallingConv::CSRet : return CallingConv::C;
1621 case OldCallingConv::Fast : return CallingConv::Fast;
1622 case OldCallingConv::Cold : return CallingConv::Cold;
1623 case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1624 case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1630 Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1631 bool debug, bool addAttrs)
1634 CurFilename = infile;
1637 AddAttributes = addAttrs;
1638 ObsoleteVarArgs = false;
1641 CurModule.CurrentModule = new Module(CurFilename);
1643 // Check to make sure the parser succeeded
1646 delete ParserResult;
1647 std::cerr << "llvm-upgrade: parse failed.\n";
1651 // Check to make sure that parsing produced a result
1652 if (!ParserResult) {
1653 std::cerr << "llvm-upgrade: no parse result.\n";
1657 // Reset ParserResult variable while saving its value for the result.
1658 Module *Result = ParserResult;
1661 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1664 if ((F = Result->getFunction("llvm.va_start"))
1665 && F->getFunctionType()->getNumParams() == 0)
1666 ObsoleteVarArgs = true;
1667 if((F = Result->getFunction("llvm.va_copy"))
1668 && F->getFunctionType()->getNumParams() == 1)
1669 ObsoleteVarArgs = true;
1672 if (ObsoleteVarArgs && NewVarArgs) {
1673 error("This file is corrupt: it uses both new and old style varargs");
1677 if(ObsoleteVarArgs) {
1678 if(Function* F = Result->getFunction("llvm.va_start")) {
1679 if (F->arg_size() != 0) {
1680 error("Obsolete va_start takes 0 argument");
1686 //bar = alloca typeof(foo)
1690 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1691 const Type* ArgTy = F->getFunctionType()->getReturnType();
1692 const Type* ArgTyPtr = PointerType::get(ArgTy);
1693 Function* NF = cast<Function>(Result->getOrInsertFunction(
1694 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1696 while (!F->use_empty()) {
1697 CallInst* CI = cast<CallInst>(F->use_back());
1698 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1699 new CallInst(NF, bar, "", CI);
1700 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1701 CI->replaceAllUsesWith(foo);
1702 CI->getParent()->getInstList().erase(CI);
1704 Result->getFunctionList().erase(F);
1707 if(Function* F = Result->getFunction("llvm.va_end")) {
1708 if(F->arg_size() != 1) {
1709 error("Obsolete va_end takes 1 argument");
1715 //bar = alloca 1 of typeof(foo)
1717 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1718 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1719 const Type* ArgTyPtr = PointerType::get(ArgTy);
1720 Function* NF = cast<Function>(Result->getOrInsertFunction(
1721 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1723 while (!F->use_empty()) {
1724 CallInst* CI = cast<CallInst>(F->use_back());
1725 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1726 new StoreInst(CI->getOperand(1), bar, CI);
1727 new CallInst(NF, bar, "", CI);
1728 CI->getParent()->getInstList().erase(CI);
1730 Result->getFunctionList().erase(F);
1733 if(Function* F = Result->getFunction("llvm.va_copy")) {
1734 if(F->arg_size() != 1) {
1735 error("Obsolete va_copy takes 1 argument");
1740 //a = alloca 1 of typeof(foo)
1741 //b = alloca 1 of typeof(foo)
1746 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1747 const Type* ArgTy = F->getFunctionType()->getReturnType();
1748 const Type* ArgTyPtr = PointerType::get(ArgTy);
1749 Function* NF = cast<Function>(Result->getOrInsertFunction(
1750 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1752 while (!F->use_empty()) {
1753 CallInst* CI = cast<CallInst>(F->use_back());
1754 SmallVector<Value *, 2> Args;
1755 Args.push_back(new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI));
1756 Args.push_back(new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI));
1757 new StoreInst(CI->getOperand(1), Args[1], CI);
1758 new CallInst(NF, Args.begin(), Args.end(), "", CI);
1759 Value* foo = new LoadInst(Args[0], "vacopy.fix.3", CI);
1760 CI->replaceAllUsesWith(foo);
1761 CI->getParent()->getInstList().erase(CI);
1763 Result->getFunctionList().erase(F);
1770 } // end llvm namespace
1772 using namespace llvm;
1777 llvm::Module *ModuleVal;
1778 llvm::Function *FunctionVal;
1779 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1780 llvm::BasicBlock *BasicBlockVal;
1781 llvm::TermInstInfo TermInstVal;
1782 llvm::InstrInfo InstVal;
1783 llvm::ConstInfo ConstVal;
1784 llvm::ValueInfo ValueVal;
1785 llvm::PATypeInfo TypeVal;
1786 llvm::TypeInfo PrimType;
1787 llvm::PHIListInfo PHIList;
1788 std::list<llvm::PATypeInfo> *TypeList;
1789 std::vector<llvm::ValueInfo> *ValueList;
1790 std::vector<llvm::ConstInfo> *ConstVector;
1793 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1794 // Represent the RHS of PHI node
1795 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1797 llvm::GlobalValue::LinkageTypes Linkage;
1805 char *StrVal; // This memory is strdup'd!
1806 llvm::ValID ValIDVal; // strdup'd memory maybe!
1808 llvm::BinaryOps BinaryOpVal;
1809 llvm::TermOps TermOpVal;
1810 llvm::MemoryOps MemOpVal;
1811 llvm::OtherOps OtherOpVal;
1812 llvm::CastOps CastOpVal;
1813 llvm::ICmpInst::Predicate IPred;
1814 llvm::FCmpInst::Predicate FPred;
1815 llvm::Module::Endianness Endianness;
1818 %type <ModuleVal> Module FunctionList
1819 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1820 %type <BasicBlockVal> BasicBlock InstructionList
1821 %type <TermInstVal> BBTerminatorInst
1822 %type <InstVal> Inst InstVal MemoryInst
1823 %type <ConstVal> ConstVal ConstExpr
1824 %type <ConstVector> ConstVector
1825 %type <ArgList> ArgList ArgListH
1826 %type <ArgVal> ArgVal
1827 %type <PHIList> PHIList
1828 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1829 %type <ValueList> IndexList // For GEP derived indices
1830 %type <TypeList> TypeListI ArgTypeListI
1831 %type <JumpTable> JumpTable
1832 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1833 %type <BoolVal> OptVolatile // 'volatile' or not
1834 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1835 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1836 %type <Linkage> OptLinkage FnDeclareLinkage
1837 %type <Endianness> BigOrLittle
1839 // ValueRef - Unresolved reference to a definition or BB
1840 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1841 %type <ValueVal> ResolvedVal // <type> <valref> pair
1843 // Tokens and types for handling constant integer values
1845 // ESINT64VAL - A negative number within long long range
1846 %token <SInt64Val> ESINT64VAL
1848 // EUINT64VAL - A positive number within uns. long long range
1849 %token <UInt64Val> EUINT64VAL
1850 %type <SInt64Val> EINT64VAL
1852 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1853 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1854 %type <SIntVal> INTVAL
1855 %token <FPVal> FPVAL // Float or Double constant
1857 // Built in types...
1858 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1859 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1860 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1861 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1863 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1864 %type <StrVal> Name OptName OptAssign
1865 %type <UIntVal> OptAlign OptCAlign
1866 %type <StrVal> OptSection SectionString
1868 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1869 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1870 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1871 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1872 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1873 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1874 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1875 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1877 %type <UIntVal> OptCallingConv
1879 // Basic Block Terminating Operators
1880 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1881 %token UNWIND EXCEPT
1884 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1885 %type <BinaryOpVal> ShiftOps
1886 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1887 %token <BinaryOpVal> AND OR XOR SHL SHR ASHR LSHR
1888 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1889 %token <OtherOpVal> ICMP FCMP
1891 // Memory Instructions
1892 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1895 %token <OtherOpVal> PHI_TOK SELECT VAARG
1896 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1897 %token VAARG_old VANEXT_old //OBSOLETE
1899 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1900 %type <IPred> IPredicates
1901 %type <FPred> FPredicates
1902 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1903 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1905 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1906 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1907 %type <CastOpVal> CastOps
1913 // Handle constant integer size restriction and conversion...
1918 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1919 error("Value too large for type");
1925 : ESINT64VAL // These have same type and can't cause problems...
1927 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1928 error("Value too large for type");
1932 // Operations that are notably excluded from this list include:
1933 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1936 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1944 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1948 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1949 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1950 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1951 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1952 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1956 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1957 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1958 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1959 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1960 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1961 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1962 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1963 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1964 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1967 : SHL | SHR | ASHR | LSHR
1971 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1972 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1975 // These are some types that allow classification if we only want a particular
1976 // thing... for example, only a signed, unsigned, or integral type.
1978 : LONG | INT | SHORT | SBYTE
1982 : ULONG | UINT | USHORT | UBYTE
1986 : SIntType | UIntType
1993 // OptAssign - Value producing statements have an optional assignment component
2003 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
2004 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
2005 | WEAK { $$ = GlobalValue::WeakLinkage; }
2006 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
2007 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
2008 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
2009 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
2010 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
2014 : /*empty*/ { $$ = lastCallingConv = OldCallingConv::C; }
2015 | CCC_TOK { $$ = lastCallingConv = OldCallingConv::C; }
2016 | CSRETCC_TOK { $$ = lastCallingConv = OldCallingConv::CSRet; }
2017 | FASTCC_TOK { $$ = lastCallingConv = OldCallingConv::Fast; }
2018 | COLDCC_TOK { $$ = lastCallingConv = OldCallingConv::Cold; }
2019 | X86_STDCALLCC_TOK { $$ = lastCallingConv = OldCallingConv::X86_StdCall; }
2020 | X86_FASTCALLCC_TOK { $$ = lastCallingConv = OldCallingConv::X86_FastCall; }
2021 | CC_TOK EUINT64VAL {
2022 if ((unsigned)$2 != $2)
2023 error("Calling conv too large");
2024 $$ = lastCallingConv = $2;
2028 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
2029 // a comma before it.
2031 : /*empty*/ { $$ = 0; }
2032 | ALIGN EUINT64VAL {
2034 if ($$ != 0 && !isPowerOf2_32($$))
2035 error("Alignment must be a power of two");
2040 : /*empty*/ { $$ = 0; }
2041 | ',' ALIGN EUINT64VAL {
2043 if ($$ != 0 && !isPowerOf2_32($$))
2044 error("Alignment must be a power of two");
2049 : SECTION STRINGCONSTANT {
2050 for (unsigned i = 0, e = strlen($2); i != e; ++i)
2051 if ($2[i] == '"' || $2[i] == '\\')
2052 error("Invalid character in section name");
2058 : /*empty*/ { $$ = 0; }
2059 | SectionString { $$ = $1; }
2062 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
2063 // is set to be the global we are processing.
2067 | ',' GlobalVarAttribute GlobalVarAttributes {}
2072 CurGV->setSection($1);
2075 | ALIGN EUINT64VAL {
2076 if ($2 != 0 && !isPowerOf2_32($2))
2077 error("Alignment must be a power of two");
2078 CurGV->setAlignment($2);
2083 //===----------------------------------------------------------------------===//
2084 // Types includes all predefined types... except void, because it can only be
2085 // used in specific contexts (function returning void for example). To have
2086 // access to it, a user must explicitly use TypesV.
2089 // TypesV includes all of 'Types', but it also includes the void type.
2093 $$.PAT = new PATypeHolder($1.T);
2094 $$.S.makeSignless();
2101 $$.PAT = new PATypeHolder($1.T);
2102 $$.S.makeSignless();
2108 if (!UpRefs.empty())
2109 error("Invalid upreference in type: " + (*$1.PAT)->getDescription());
2115 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
2116 | LONG | ULONG | FLOAT | DOUBLE | LABEL
2119 // Derived types are added later...
2122 $$.PAT = new PATypeHolder($1.T);
2126 $$.PAT = new PATypeHolder(OpaqueType::get());
2127 $$.S.makeSignless();
2129 | SymbolicValueRef { // Named types are also simple types...
2130 $$.S.copy(getTypeSign($1));
2131 const Type* tmp = getType($1);
2132 $$.PAT = new PATypeHolder(tmp);
2134 | '\\' EUINT64VAL { // Type UpReference
2135 if ($2 > (uint64_t)~0U)
2136 error("Value out of range");
2137 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
2138 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
2139 $$.PAT = new PATypeHolder(OT);
2140 $$.S.makeSignless();
2141 UR_OUT("New Upreference!\n");
2143 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
2144 $$.S.makeComposite($1.S);
2145 std::vector<const Type*> Params;
2146 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
2147 E = $3->end(); I != E; ++I) {
2148 Params.push_back(I->PAT->get());
2151 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
2152 if (isVarArg) Params.pop_back();
2154 ParamAttrsList *PAL = 0;
2155 if (lastCallingConv == OldCallingConv::CSRet) {
2156 ParamAttrsVector Attrs;
2157 ParamAttrsWithIndex PAWI;
2158 PAWI.index = 1; PAWI.attrs = ParamAttr::StructRet; // first arg
2159 Attrs.push_back(PAWI);
2160 PAL = ParamAttrsList::get(Attrs);
2163 const FunctionType *FTy =
2164 FunctionType::get($1.PAT->get(), Params, isVarArg, PAL);
2166 $$.PAT = new PATypeHolder( HandleUpRefs(FTy, $$.S) );
2167 delete $1.PAT; // Delete the return type handle
2168 delete $3; // Delete the argument list
2170 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
2171 $$.S.makeComposite($4.S);
2172 $$.PAT = new PATypeHolder(HandleUpRefs(ArrayType::get($4.PAT->get(),
2173 (unsigned)$2), $$.S));
2176 | '<' EUINT64VAL 'x' UpRTypes '>' { // Vector type?
2177 const llvm::Type* ElemTy = $4.PAT->get();
2178 if ((unsigned)$2 != $2)
2179 error("Unsigned result not equal to signed result");
2180 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
2181 error("Elements of a VectorType must be integer or floating point");
2182 if (!isPowerOf2_32($2))
2183 error("VectorType length should be a power of 2");
2184 $$.S.makeComposite($4.S);
2185 $$.PAT = new PATypeHolder(HandleUpRefs(VectorType::get(ElemTy,
2186 (unsigned)$2), $$.S));
2189 | '{' TypeListI '}' { // Structure type?
2190 std::vector<const Type*> Elements;
2191 $$.S.makeComposite();
2192 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
2193 E = $2->end(); I != E; ++I) {
2194 Elements.push_back(I->PAT->get());
2197 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements), $$.S));
2200 | '{' '}' { // Empty structure type?
2201 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>()));
2202 $$.S.makeComposite();
2204 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
2205 $$.S.makeComposite();
2206 std::vector<const Type*> Elements;
2207 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
2208 E = $3->end(); I != E; ++I) {
2209 Elements.push_back(I->PAT->get());
2213 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true),
2217 | '<' '{' '}' '>' { // Empty packed structure type?
2218 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
2219 $$.S.makeComposite();
2221 | UpRTypes '*' { // Pointer type?
2222 if ($1.PAT->get() == Type::LabelTy)
2223 error("Cannot form a pointer to a basic block");
2224 $$.S.makeComposite($1.S);
2225 $$.PAT = new PATypeHolder(HandleUpRefs(PointerType::get($1.PAT->get()),
2231 // TypeList - Used for struct declarations and as a basis for function type
2232 // declaration type lists
2236 $$ = new std::list<PATypeInfo>();
2239 | TypeListI ',' UpRTypes {
2240 ($$=$1)->push_back($3);
2244 // ArgTypeList - List of types for a function type declaration...
2247 | TypeListI ',' DOTDOTDOT {
2249 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2250 VoidTI.S.makeSignless();
2251 ($$=$1)->push_back(VoidTI);
2254 $$ = new std::list<PATypeInfo>();
2256 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2257 VoidTI.S.makeSignless();
2258 $$->push_back(VoidTI);
2261 $$ = new std::list<PATypeInfo>();
2265 // ConstVal - The various declarations that go into the constant pool. This
2266 // production is used ONLY to represent constants that show up AFTER a 'const',
2267 // 'constant' or 'global' token at global scope. Constants that can be inlined
2268 // into other expressions (such as integers and constexprs) are handled by the
2269 // ResolvedVal, ValueRef and ConstValueRef productions.
2272 : Types '[' ConstVector ']' { // Nonempty unsized arr
2273 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2275 error("Cannot make array constant with type: '" +
2276 $1.PAT->get()->getDescription() + "'");
2277 const Type *ETy = ATy->getElementType();
2278 int NumElements = ATy->getNumElements();
2280 // Verify that we have the correct size...
2281 if (NumElements != -1 && NumElements != (int)$3->size())
2282 error("Type mismatch: constant sized array initialized with " +
2283 utostr($3->size()) + " arguments, but has size of " +
2284 itostr(NumElements) + "");
2286 // Verify all elements are correct type!
2287 std::vector<Constant*> Elems;
2288 for (unsigned i = 0; i < $3->size(); i++) {
2289 Constant *C = (*$3)[i].C;
2290 const Type* ValTy = C->getType();
2292 error("Element #" + utostr(i) + " is not of type '" +
2293 ETy->getDescription() +"' as required!\nIt is of type '"+
2294 ValTy->getDescription() + "'");
2297 $$.C = ConstantArray::get(ATy, Elems);
2303 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2305 error("Cannot make array constant with type: '" +
2306 $1.PAT->get()->getDescription() + "'");
2307 int NumElements = ATy->getNumElements();
2308 if (NumElements != -1 && NumElements != 0)
2309 error("Type mismatch: constant sized array initialized with 0"
2310 " arguments, but has size of " + itostr(NumElements) +"");
2311 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
2315 | Types 'c' STRINGCONSTANT {
2316 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2318 error("Cannot make array constant with type: '" +
2319 $1.PAT->get()->getDescription() + "'");
2320 int NumElements = ATy->getNumElements();
2321 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
2322 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
2323 error("String arrays require type i8, not '" + ETy->getDescription() +
2325 char *EndStr = UnEscapeLexed($3, true);
2326 if (NumElements != -1 && NumElements != (EndStr-$3))
2327 error("Can't build string constant of size " +
2328 itostr((int)(EndStr-$3)) + " when array has size " +
2329 itostr(NumElements) + "");
2330 std::vector<Constant*> Vals;
2331 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
2332 Vals.push_back(ConstantInt::get(ETy, *C));
2334 $$.C = ConstantArray::get(ATy, Vals);
2338 | Types '<' ConstVector '>' { // Nonempty unsized arr
2339 const VectorType *PTy = dyn_cast<VectorType>($1.PAT->get());
2341 error("Cannot make packed constant with type: '" +
2342 $1.PAT->get()->getDescription() + "'");
2343 const Type *ETy = PTy->getElementType();
2344 int NumElements = PTy->getNumElements();
2345 // Verify that we have the correct size...
2346 if (NumElements != -1 && NumElements != (int)$3->size())
2347 error("Type mismatch: constant sized packed initialized with " +
2348 utostr($3->size()) + " arguments, but has size of " +
2349 itostr(NumElements) + "");
2350 // Verify all elements are correct type!
2351 std::vector<Constant*> Elems;
2352 for (unsigned i = 0; i < $3->size(); i++) {
2353 Constant *C = (*$3)[i].C;
2354 const Type* ValTy = C->getType();
2356 error("Element #" + utostr(i) + " is not of type '" +
2357 ETy->getDescription() +"' as required!\nIt is of type '"+
2358 ValTy->getDescription() + "'");
2361 $$.C = ConstantVector::get(PTy, Elems);
2366 | Types '{' ConstVector '}' {
2367 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2369 error("Cannot make struct constant with type: '" +
2370 $1.PAT->get()->getDescription() + "'");
2371 if ($3->size() != STy->getNumContainedTypes())
2372 error("Illegal number of initializers for structure type");
2374 // Check to ensure that constants are compatible with the type initializer!
2375 std::vector<Constant*> Fields;
2376 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2377 Constant *C = (*$3)[i].C;
2378 if (C->getType() != STy->getElementType(i))
2379 error("Expected type '" + STy->getElementType(i)->getDescription() +
2380 "' for element #" + utostr(i) + " of structure initializer");
2381 Fields.push_back(C);
2383 $$.C = ConstantStruct::get(STy, Fields);
2389 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2391 error("Cannot make struct constant with type: '" +
2392 $1.PAT->get()->getDescription() + "'");
2393 if (STy->getNumContainedTypes() != 0)
2394 error("Illegal number of initializers for structure type");
2395 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2399 | Types '<' '{' ConstVector '}' '>' {
2400 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2402 error("Cannot make packed struct constant with type: '" +
2403 $1.PAT->get()->getDescription() + "'");
2404 if ($4->size() != STy->getNumContainedTypes())
2405 error("Illegal number of initializers for packed structure type");
2407 // Check to ensure that constants are compatible with the type initializer!
2408 std::vector<Constant*> Fields;
2409 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2410 Constant *C = (*$4)[i].C;
2411 if (C->getType() != STy->getElementType(i))
2412 error("Expected type '" + STy->getElementType(i)->getDescription() +
2413 "' for element #" + utostr(i) + " of packed struct initializer");
2414 Fields.push_back(C);
2416 $$.C = ConstantStruct::get(STy, Fields);
2421 | Types '<' '{' '}' '>' {
2422 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2424 error("Cannot make packed struct constant with type: '" +
2425 $1.PAT->get()->getDescription() + "'");
2426 if (STy->getNumContainedTypes() != 0)
2427 error("Illegal number of initializers for packed structure type");
2428 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2433 const PointerType *PTy = dyn_cast<PointerType>($1.PAT->get());
2435 error("Cannot make null pointer constant with type: '" +
2436 $1.PAT->get()->getDescription() + "'");
2437 $$.C = ConstantPointerNull::get(PTy);
2442 $$.C = UndefValue::get($1.PAT->get());
2446 | Types SymbolicValueRef {
2447 const PointerType *Ty = dyn_cast<PointerType>($1.PAT->get());
2449 error("Global const reference must be a pointer type, not" +
2450 $1.PAT->get()->getDescription());
2452 // ConstExprs can exist in the body of a function, thus creating
2453 // GlobalValues whenever they refer to a variable. Because we are in
2454 // the context of a function, getExistingValue will search the functions
2455 // symbol table instead of the module symbol table for the global symbol,
2456 // which throws things all off. To get around this, we just tell
2457 // getExistingValue that we are at global scope here.
2459 Function *SavedCurFn = CurFun.CurrentFunction;
2460 CurFun.CurrentFunction = 0;
2462 Value *V = getExistingValue(Ty, $2);
2463 CurFun.CurrentFunction = SavedCurFn;
2465 // If this is an initializer for a constant pointer, which is referencing a
2466 // (currently) undefined variable, create a stub now that shall be replaced
2467 // in the future with the right type of variable.
2470 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2471 const PointerType *PT = cast<PointerType>(Ty);
2473 // First check to see if the forward references value is already created!
2474 PerModuleInfo::GlobalRefsType::iterator I =
2475 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2477 if (I != CurModule.GlobalRefs.end()) {
2478 V = I->second; // Placeholder already exists, use it...
2482 if ($2.Type == ValID::NameVal) Name = $2.Name;
2484 // Create the forward referenced global.
2486 if (const FunctionType *FTy =
2487 dyn_cast<FunctionType>(PT->getElementType())) {
2488 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2489 CurModule.CurrentModule);
2491 GV = new GlobalVariable(PT->getElementType(), false,
2492 GlobalValue::ExternalLinkage, 0,
2493 Name, CurModule.CurrentModule);
2496 // Keep track of the fact that we have a forward ref to recycle it
2497 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2501 $$.C = cast<GlobalValue>(V);
2503 delete $1.PAT; // Free the type handle
2506 if ($1.PAT->get() != $2.C->getType())
2507 error("Mismatched types for constant expression");
2512 | Types ZEROINITIALIZER {
2513 const Type *Ty = $1.PAT->get();
2514 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2515 error("Cannot create a null initialized value of this type");
2516 $$.C = Constant::getNullValue(Ty);
2520 | SIntType EINT64VAL { // integral constants
2521 const Type *Ty = $1.T;
2522 if (!ConstantInt::isValueValidForType(Ty, $2))
2523 error("Constant value doesn't fit in type");
2524 $$.C = ConstantInt::get(Ty, $2);
2527 | UIntType EUINT64VAL { // integral constants
2528 const Type *Ty = $1.T;
2529 if (!ConstantInt::isValueValidForType(Ty, $2))
2530 error("Constant value doesn't fit in type");
2531 $$.C = ConstantInt::get(Ty, $2);
2532 $$.S.makeUnsigned();
2534 | BOOL TRUETOK { // Boolean constants
2535 $$.C = ConstantInt::get(Type::Int1Ty, true);
2536 $$.S.makeUnsigned();
2538 | BOOL FALSETOK { // Boolean constants
2539 $$.C = ConstantInt::get(Type::Int1Ty, false);
2540 $$.S.makeUnsigned();
2542 | FPType FPVAL { // Float & Double constants
2543 if (!ConstantFP::isValueValidForType($1.T, $2))
2544 error("Floating point constant invalid for type");
2545 $$.C = ConstantFP::get($1.T, $2);
2546 $$.S.makeSignless();
2551 : CastOps '(' ConstVal TO Types ')' {
2552 const Type* SrcTy = $3.C->getType();
2553 const Type* DstTy = $5.PAT->get();
2554 Signedness SrcSign($3.S);
2555 Signedness DstSign($5.S);
2556 if (!SrcTy->isFirstClassType())
2557 error("cast constant expression from a non-primitive type: '" +
2558 SrcTy->getDescription() + "'");
2559 if (!DstTy->isFirstClassType())
2560 error("cast constant expression to a non-primitive type: '" +
2561 DstTy->getDescription() + "'");
2562 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2566 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2567 const Type *Ty = $3.C->getType();
2568 if (!isa<PointerType>(Ty))
2569 error("GetElementPtr requires a pointer operand");
2571 std::vector<Constant*> CIndices;
2572 upgradeGEPCEIndices($3.C->getType(), $4, CIndices);
2575 $$.C = ConstantExpr::getGetElementPtr($3.C, &CIndices[0], CIndices.size());
2576 $$.S.copy(getElementSign($3, CIndices));
2578 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2579 if (!$3.C->getType()->isInteger() ||
2580 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2581 error("Select condition must be bool type");
2582 if ($5.C->getType() != $7.C->getType())
2583 error("Select operand types must match");
2584 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2587 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2588 const Type *Ty = $3.C->getType();
2589 if (Ty != $5.C->getType())
2590 error("Binary operator types must match");
2591 // First, make sure we're dealing with the right opcode by upgrading from
2592 // obsolete versions.
2593 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2595 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2596 // To retain backward compatibility with these early compilers, we emit a
2597 // cast to the appropriate integer type automatically if we are in the
2598 // broken case. See PR424 for more information.
2599 if (!isa<PointerType>(Ty)) {
2600 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2602 const Type *IntPtrTy = 0;
2603 switch (CurModule.CurrentModule->getPointerSize()) {
2604 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2605 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2606 default: error("invalid pointer binary constant expr");
2608 $$.C = ConstantExpr::get(Opcode,
2609 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2610 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2611 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2615 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2616 const Type* Ty = $3.C->getType();
2617 if (Ty != $5.C->getType())
2618 error("Logical operator types must match");
2619 if (!Ty->isInteger()) {
2620 if (!isa<VectorType>(Ty) ||
2621 !cast<VectorType>(Ty)->getElementType()->isInteger())
2622 error("Logical operator requires integer operands");
2624 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2625 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2628 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2629 const Type* Ty = $3.C->getType();
2630 if (Ty != $5.C->getType())
2631 error("setcc operand types must match");
2632 unsigned short pred;
2633 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2634 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2635 $$.S.makeUnsigned();
2637 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2638 if ($4.C->getType() != $6.C->getType())
2639 error("icmp operand types must match");
2640 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2641 $$.S.makeUnsigned();
2643 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2644 if ($4.C->getType() != $6.C->getType())
2645 error("fcmp operand types must match");
2646 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2647 $$.S.makeUnsigned();
2649 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2650 if (!$5.C->getType()->isInteger() ||
2651 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2652 error("Shift count for shift constant must be unsigned byte");
2653 const Type* Ty = $3.C->getType();
2654 if (!$3.C->getType()->isInteger())
2655 error("Shift constant expression requires integer operand");
2656 Constant *ShiftAmt = ConstantExpr::getZExt($5.C, Ty);
2657 $$.C = ConstantExpr::get(getBinaryOp($1, Ty, $3.S), $3.C, ShiftAmt);
2660 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2661 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2662 error("Invalid extractelement operands");
2663 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2664 $$.S.copy($3.S.get(0));
2666 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2667 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2668 error("Invalid insertelement operands");
2669 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2672 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2673 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2674 error("Invalid shufflevector operands");
2675 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2681 // ConstVector - A list of comma separated constants.
2683 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2685 $$ = new std::vector<ConstInfo>();
2691 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2693 : GLOBAL { $$ = false; }
2694 | CONSTANT { $$ = true; }
2698 //===----------------------------------------------------------------------===//
2699 // Rules to match Modules
2700 //===----------------------------------------------------------------------===//
2702 // Module rule: Capture the result of parsing the whole file into a result
2707 $$ = ParserResult = $1;
2708 CurModule.ModuleDone();
2712 // FunctionList - A list of functions, preceeded by a constant pool.
2715 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2716 | FunctionList FunctionProto { $$ = $1; }
2717 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2718 | FunctionList IMPLEMENTATION { $$ = $1; }
2720 $$ = CurModule.CurrentModule;
2721 // Emit an error if there are any unresolved types left.
2722 if (!CurModule.LateResolveTypes.empty()) {
2723 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2724 if (DID.Type == ValID::NameVal) {
2725 error("Reference to an undefined type: '"+DID.getName() + "'");
2727 error("Reference to an undefined type: #" + itostr(DID.Num));
2733 // ConstPool - Constants with optional names assigned to them.
2735 : ConstPool OptAssign TYPE TypesV {
2736 // Eagerly resolve types. This is not an optimization, this is a
2737 // requirement that is due to the fact that we could have this:
2739 // %list = type { %list * }
2740 // %list = type { %list * } ; repeated type decl
2742 // If types are not resolved eagerly, then the two types will not be
2743 // determined to be the same type!
2745 ResolveTypeTo($2, $4.PAT->get(), $4.S);
2747 if (!setTypeName($4, $2) && !$2) {
2748 // If this is a numbered type that is not a redefinition, add it to the
2750 CurModule.Types.push_back($4.PAT->get());
2751 CurModule.TypeSigns.push_back($4.S);
2755 | ConstPool FunctionProto { // Function prototypes can be in const pool
2757 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2759 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2761 error("Global value initializer is not a constant");
2762 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C, $5.S);
2763 } GlobalVarAttributes {
2766 | ConstPool OptAssign EXTERNAL GlobalType Types {
2767 const Type *Ty = $5.PAT->get();
2768 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0,
2771 } GlobalVarAttributes {
2774 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2775 const Type *Ty = $5.PAT->get();
2776 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0,
2779 } GlobalVarAttributes {
2782 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2783 const Type *Ty = $5.PAT->get();
2785 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0,
2788 } GlobalVarAttributes {
2791 | ConstPool TARGET TargetDefinition {
2793 | ConstPool DEPLIBS '=' LibrariesDefinition {
2795 | /* empty: end of list */ {
2801 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2802 char *EndStr = UnEscapeLexed($1, true);
2803 std::string NewAsm($1, EndStr);
2806 if (AsmSoFar.empty())
2807 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2809 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2814 : BIG { $$ = Module::BigEndian; }
2815 | LITTLE { $$ = Module::LittleEndian; }
2819 : ENDIAN '=' BigOrLittle {
2820 CurModule.setEndianness($3);
2822 | POINTERSIZE '=' EUINT64VAL {
2824 CurModule.setPointerSize(Module::Pointer32);
2826 CurModule.setPointerSize(Module::Pointer64);
2828 error("Invalid pointer size: '" + utostr($3) + "'");
2830 | TRIPLE '=' STRINGCONSTANT {
2831 CurModule.CurrentModule->setTargetTriple($3);
2834 | DATALAYOUT '=' STRINGCONSTANT {
2835 CurModule.CurrentModule->setDataLayout($3);
2845 : LibList ',' STRINGCONSTANT {
2846 CurModule.CurrentModule->addLibrary($3);
2850 CurModule.CurrentModule->addLibrary($1);
2853 | /* empty: end of list */ { }
2856 //===----------------------------------------------------------------------===//
2857 // Rules to match Function Headers
2858 //===----------------------------------------------------------------------===//
2861 : VAR_ID | STRINGCONSTANT
2866 | /*empty*/ { $$ = 0; }
2871 if ($1.PAT->get() == Type::VoidTy)
2872 error("void typed arguments are invalid");
2873 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2878 : ArgListH ',' ArgVal {
2884 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2891 : ArgListH { $$ = $1; }
2892 | ArgListH ',' DOTDOTDOT {
2895 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2896 VoidTI.S.makeSignless();
2897 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2900 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2902 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2903 VoidTI.S.makeSignless();
2904 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2906 | /* empty */ { $$ = 0; }
2910 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2912 std::string FunctionName($3);
2913 free($3); // Free strdup'd memory!
2915 const Type* RetTy = $2.PAT->get();
2917 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2918 error("LLVM functions cannot return aggregate types");
2921 FTySign.makeComposite($2.S);
2922 std::vector<const Type*> ParamTyList;
2924 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2925 // i8*. We check here for those names and override the parameter list
2926 // types to ensure the prototype is correct.
2927 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2928 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2929 } else if (FunctionName == "llvm.va_copy") {
2930 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2931 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2932 } else if ($5) { // If there are arguments...
2933 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2934 I = $5->begin(), E = $5->end(); I != E; ++I) {
2935 const Type *Ty = I->first.PAT->get();
2936 ParamTyList.push_back(Ty);
2937 FTySign.add(I->first.S);
2941 bool isVarArg = ParamTyList.size() && ParamTyList.back() == Type::VoidTy;
2943 ParamTyList.pop_back();
2945 // Convert the CSRet calling convention into the corresponding parameter
2947 ParamAttrsList *PAL = 0;
2948 if ($1 == OldCallingConv::CSRet) {
2949 ParamAttrsVector Attrs;
2950 ParamAttrsWithIndex PAWI;
2951 PAWI.index = 1; PAWI.attrs = ParamAttr::StructRet; // first arg
2952 Attrs.push_back(PAWI);
2953 PAL = ParamAttrsList::get(Attrs);
2956 const FunctionType *FT =
2957 FunctionType::get(RetTy, ParamTyList, isVarArg, PAL);
2958 const PointerType *PFT = PointerType::get(FT);
2962 if (!FunctionName.empty()) {
2963 ID = ValID::create((char*)FunctionName.c_str());
2965 ID = ValID::create((int)CurModule.Values[PFT].size());
2967 ID.S.makeComposite(FTySign);
2970 Module* M = CurModule.CurrentModule;
2972 // See if this function was forward referenced. If so, recycle the object.
2973 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2974 // Move the function to the end of the list, from whereever it was
2975 // previously inserted.
2976 Fn = cast<Function>(FWRef);
2977 M->getFunctionList().remove(Fn);
2978 M->getFunctionList().push_back(Fn);
2979 } else if (!FunctionName.empty()) {
2980 GlobalValue *Conflict = M->getFunction(FunctionName);
2982 Conflict = M->getNamedGlobal(FunctionName);
2983 if (Conflict && PFT == Conflict->getType()) {
2984 if (!CurFun.isDeclare && !Conflict->isDeclaration()) {
2985 // We have two function definitions that conflict, same type, same
2986 // name. We should really check to make sure that this is the result
2987 // of integer type planes collapsing and generate an error if it is
2988 // not, but we'll just rename on the assumption that it is. However,
2989 // let's do it intelligently and rename the internal linkage one
2991 std::string NewName(makeNameUnique(FunctionName));
2992 if (Conflict->hasInternalLinkage()) {
2993 Conflict->setName(NewName);
2995 makeRenameMapKey(FunctionName, Conflict->getType(), ID.S);
2996 CurModule.RenameMap[Key] = NewName;
2997 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2998 InsertValue(Fn, CurModule.Values);
3000 Fn = new Function(FT, CurFun.Linkage, NewName, M);
3001 InsertValue(Fn, CurModule.Values);
3003 makeRenameMapKey(FunctionName, PFT, ID.S);
3004 CurModule.RenameMap[Key] = NewName;
3007 // If they are not both definitions, then just use the function we
3008 // found since the types are the same.
3009 Fn = cast<Function>(Conflict);
3011 // Make sure to strip off any argument names so we can't get
3013 if (Fn->isDeclaration())
3014 for (Function::arg_iterator AI = Fn->arg_begin(),
3015 AE = Fn->arg_end(); AI != AE; ++AI)
3018 } else if (Conflict) {
3019 // We have two globals with the same name and different types.
3020 // Previously, this was permitted because the symbol table had
3021 // "type planes" and names only needed to be distinct within a
3022 // type plane. After PR411 was fixed, this is no loner the case.
3023 // To resolve this we must rename one of the two.
3024 if (Conflict->hasInternalLinkage()) {
3025 // We can safely rename the Conflict.
3027 makeRenameMapKey(Conflict->getName(), Conflict->getType(),
3028 CurModule.NamedValueSigns[Conflict->getName()]);
3029 Conflict->setName(makeNameUnique(Conflict->getName()));
3030 CurModule.RenameMap[Key] = Conflict->getName();
3031 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
3032 InsertValue(Fn, CurModule.Values);
3034 // We can't quietly rename either of these things, but we must
3035 // rename one of them. Only if the function's linkage is internal can
3036 // we forgo a warning message about the renamed function.
3037 std::string NewName = makeNameUnique(FunctionName);
3038 if (CurFun.Linkage != GlobalValue::InternalLinkage) {
3039 warning("Renaming function '" + FunctionName + "' as '" + NewName +
3040 "' may cause linkage errors");
3042 // Elect to rename the thing we're now defining.
3043 Fn = new Function(FT, CurFun.Linkage, NewName, M);
3044 InsertValue(Fn, CurModule.Values);
3045 RenameMapKey Key = makeRenameMapKey(FunctionName, PFT, ID.S);
3046 CurModule.RenameMap[Key] = NewName;
3049 // There's no conflict, just define the function
3050 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
3051 InsertValue(Fn, CurModule.Values);
3054 // There's no conflict, just define the function
3055 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
3056 InsertValue(Fn, CurModule.Values);
3060 CurFun.FunctionStart(Fn);
3062 if (CurFun.isDeclare) {
3063 // If we have declaration, always overwrite linkage. This will allow us
3064 // to correctly handle cases, when pointer to function is passed as
3065 // argument to another function.
3066 Fn->setLinkage(CurFun.Linkage);
3068 Fn->setCallingConv(upgradeCallingConv($1));
3069 Fn->setAlignment($8);
3075 // Add all of the arguments we parsed to the function...
3076 if ($5) { // Is null if empty...
3077 if (isVarArg) { // Nuke the last entry
3078 assert($5->back().first.PAT->get() == Type::VoidTy &&
3079 $5->back().second == 0 && "Not a varargs marker");
3080 delete $5->back().first.PAT;
3081 $5->pop_back(); // Delete the last entry
3083 Function::arg_iterator ArgIt = Fn->arg_begin();
3084 Function::arg_iterator ArgEnd = Fn->arg_end();
3085 std::vector<std::pair<PATypeInfo,char*> >::iterator I = $5->begin();
3086 std::vector<std::pair<PATypeInfo,char*> >::iterator E = $5->end();
3087 for ( ; I != E && ArgIt != ArgEnd; ++I, ++ArgIt) {
3088 delete I->first.PAT; // Delete the typeholder...
3089 ValueInfo VI; VI.V = ArgIt; VI.S.copy(I->first.S);
3090 setValueName(VI, I->second); // Insert arg into symtab...
3093 delete $5; // We're now done with the argument list
3095 lastCallingConv = OldCallingConv::C;
3100 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
3104 : OptLinkage { CurFun.Linkage = $1; } FunctionHeaderH BEGIN {
3105 $$ = CurFun.CurrentFunction;
3107 // Make sure that we keep track of the linkage type even if there was a
3108 // previous "declare".
3114 : ENDTOK | '}' // Allow end of '}' to end a function
3118 : BasicBlockList END {
3123 : /*default*/ { $$ = GlobalValue::ExternalLinkage; }
3124 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
3125 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
3129 : DECLARE { CurFun.isDeclare = true; }
3130 FnDeclareLinkage { CurFun.Linkage = $3; } FunctionHeaderH {
3131 $$ = CurFun.CurrentFunction;
3132 CurFun.FunctionDone();
3137 //===----------------------------------------------------------------------===//
3138 // Rules to match Basic Blocks
3139 //===----------------------------------------------------------------------===//
3142 : /* empty */ { $$ = false; }
3143 | SIDEEFFECT { $$ = true; }
3147 // A reference to a direct constant
3148 : ESINT64VAL { $$ = ValID::create($1); }
3149 | EUINT64VAL { $$ = ValID::create($1); }
3150 | FPVAL { $$ = ValID::create($1); }
3152 $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true));
3153 $$.S.makeUnsigned();
3156 $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false));
3157 $$.S.makeUnsigned();
3159 | NULL_TOK { $$ = ValID::createNull(); }
3160 | UNDEF { $$ = ValID::createUndef(); }
3161 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
3162 | '<' ConstVector '>' { // Nonempty unsized packed vector
3163 const Type *ETy = (*$2)[0].C->getType();
3164 int NumElements = $2->size();
3165 VectorType* pt = VectorType::get(ETy, NumElements);
3166 $$.S.makeComposite((*$2)[0].S);
3167 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt, $$.S));
3169 // Verify all elements are correct type!
3170 std::vector<Constant*> Elems;
3171 for (unsigned i = 0; i < $2->size(); i++) {
3172 Constant *C = (*$2)[i].C;
3173 const Type *CTy = C->getType();
3175 error("Element #" + utostr(i) + " is not of type '" +
3176 ETy->getDescription() +"' as required!\nIt is of type '" +
3177 CTy->getDescription() + "'");
3180 $$ = ValID::create(ConstantVector::get(pt, Elems));
3181 delete PTy; delete $2;
3184 $$ = ValID::create($1.C);
3187 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
3188 char *End = UnEscapeLexed($3, true);
3189 std::string AsmStr = std::string($3, End);
3190 End = UnEscapeLexed($5, true);
3191 std::string Constraints = std::string($5, End);
3192 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
3198 // SymbolicValueRef - Reference to one of two ways of symbolically refering to // another value.
3201 : INTVAL { $$ = ValID::create($1); $$.S.makeSignless(); }
3202 | Name { $$ = ValID::create($1); $$.S.makeSignless(); }
3205 // ValueRef - A reference to a definition... either constant or symbolic
3207 : SymbolicValueRef | ConstValueRef
3211 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
3212 // type immediately preceeds the value reference, and allows complex constant
3213 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
3216 const Type *Ty = $1.PAT->get();
3218 $$.V = getVal(Ty, $2);
3225 : BasicBlockList BasicBlock {
3228 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
3233 // Basic blocks are terminated by branching instructions:
3234 // br, br/cc, switch, ret
3237 : InstructionList OptAssign BBTerminatorInst {
3238 ValueInfo VI; VI.V = $3.TI; VI.S.copy($3.S);
3239 setValueName(VI, $2);
3241 $1->getInstList().push_back($3.TI);
3248 : InstructionList Inst {
3250 $1->getInstList().push_back($2.I);
3254 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++),true);
3255 // Make sure to move the basic block to the correct location in the
3256 // function, instead of leaving it inserted wherever it was first
3258 Function::BasicBlockListType &BBL =
3259 CurFun.CurrentFunction->getBasicBlockList();
3260 BBL.splice(BBL.end(), BBL, $$);
3263 $$ = CurBB = getBBVal(ValID::create($1), true);
3264 // Make sure to move the basic block to the correct location in the
3265 // function, instead of leaving it inserted wherever it was first
3267 Function::BasicBlockListType &BBL =
3268 CurFun.CurrentFunction->getBasicBlockList();
3269 BBL.splice(BBL.end(), BBL, $$);
3273 Unwind : UNWIND | EXCEPT;
3276 : RET ResolvedVal { // Return with a result...
3277 $$.TI = new ReturnInst($2.V);
3278 $$.S.makeSignless();
3280 | RET VOID { // Return with no result...
3281 $$.TI = new ReturnInst();
3282 $$.S.makeSignless();
3284 | BR LABEL ValueRef { // Unconditional Branch...
3285 BasicBlock* tmpBB = getBBVal($3);
3286 $$.TI = new BranchInst(tmpBB);
3287 $$.S.makeSignless();
3288 } // Conditional Branch...
3289 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
3290 $6.S.makeSignless();
3291 $9.S.makeSignless();
3292 BasicBlock* tmpBBA = getBBVal($6);
3293 BasicBlock* tmpBBB = getBBVal($9);
3294 $3.S.makeUnsigned();
3295 Value* tmpVal = getVal(Type::Int1Ty, $3);
3296 $$.TI = new BranchInst(tmpBBA, tmpBBB, tmpVal);
3297 $$.S.makeSignless();
3299 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
3301 Value* tmpVal = getVal($2.T, $3);
3302 $6.S.makeSignless();
3303 BasicBlock* tmpBB = getBBVal($6);
3304 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
3306 $$.S.makeSignless();
3307 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
3309 for (; I != E; ++I) {
3310 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
3311 S->addCase(CI, I->second);
3313 error("Switch case is constant, but not a simple integer");
3317 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
3319 Value* tmpVal = getVal($2.T, $3);
3320 $6.S.makeSignless();
3321 BasicBlock* tmpBB = getBBVal($6);
3322 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
3324 $$.S.makeSignless();
3326 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
3327 TO LABEL ValueRef Unwind LABEL ValueRef {
3328 const PointerType *PFTy;
3329 const FunctionType *Ty;
3332 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3333 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3334 // Pull out the types of all of the arguments...
3335 std::vector<const Type*> ParamTypes;
3336 FTySign.makeComposite($3.S);
3338 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3340 ParamTypes.push_back((*I).V->getType());
3344 ParamAttrsList *PAL = 0;
3345 if ($2 == OldCallingConv::CSRet) {
3346 ParamAttrsVector Attrs;
3347 ParamAttrsWithIndex PAWI;
3348 PAWI.index = 1; PAWI.attrs = ParamAttr::StructRet; // first arg
3349 Attrs.push_back(PAWI);
3350 PAL = ParamAttrsList::get(Attrs);
3352 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3353 if (isVarArg) ParamTypes.pop_back();
3354 Ty = FunctionType::get($3.PAT->get(), ParamTypes, isVarArg, PAL);
3355 PFTy = PointerType::get(Ty);
3359 // Get the signedness of the result type. $3 is the pointer to the
3360 // function type so we get the 0th element to extract the function type,
3361 // and then the 0th element again to get the result type.
3362 $$.S.copy($3.S.get(0).get(0));
3365 $4.S.makeComposite(FTySign);
3366 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3367 BasicBlock *Normal = getBBVal($10);
3368 BasicBlock *Except = getBBVal($13);
3370 // Create the call node...
3371 if (!$6) { // Has no arguments?
3372 $$.TI = new InvokeInst(V, Normal, Except, 0, 0);
3373 } else { // Has arguments?
3374 // Loop through FunctionType's arguments and ensure they are specified
3377 FunctionType::param_iterator I = Ty->param_begin();
3378 FunctionType::param_iterator E = Ty->param_end();
3379 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3381 std::vector<Value*> Args;
3382 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
3383 if ((*ArgI).V->getType() != *I)
3384 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3385 (*I)->getDescription() + "'");
3386 Args.push_back((*ArgI).V);
3389 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
3390 error("Invalid number of parameters detected");
3392 $$.TI = new InvokeInst(V, Normal, Except, &Args[0], Args.size());
3394 cast<InvokeInst>($$.TI)->setCallingConv(upgradeCallingConv($2));
3397 lastCallingConv = OldCallingConv::C;
3400 $$.TI = new UnwindInst();
3401 $$.S.makeSignless();
3404 $$.TI = new UnreachableInst();
3405 $$.S.makeSignless();
3410 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
3413 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
3416 error("May only switch on a constant pool value");
3418 $6.S.makeSignless();
3419 BasicBlock* tmpBB = getBBVal($6);
3420 $$->push_back(std::make_pair(V, tmpBB));
3422 | IntType ConstValueRef ',' LABEL ValueRef {
3423 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3425 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
3428 error("May only switch on a constant pool value");
3430 $5.S.makeSignless();
3431 BasicBlock* tmpBB = getBBVal($5);
3432 $$->push_back(std::make_pair(V, tmpBB));
3437 : OptAssign InstVal {
3440 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
3441 if (BCI->getSrcTy() == BCI->getDestTy() &&
3442 BCI->getOperand(0)->getName() == $1)
3443 // This is a useless bit cast causing a name redefinition. It is
3444 // a bit cast from a type to the same type of an operand with the
3445 // same name as the name we would give this instruction. Since this
3446 // instruction results in no code generation, it is safe to omit
3447 // the instruction. This situation can occur because of collapsed
3448 // type planes. For example:
3449 // %X = add int %Y, %Z
3450 // %X = cast int %Y to uint
3451 // After upgrade, this looks like:
3452 // %X = add i32 %Y, %Z
3453 // %X = bitcast i32 to i32
3454 // The bitcast is clearly useless so we omit it.
3458 $$.S.makeSignless();
3460 ValueInfo VI; VI.V = $2.I; VI.S.copy($2.S);
3461 setValueName(VI, $1);
3467 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3468 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3471 Value* tmpVal = getVal($1.PAT->get(), $3);
3472 $5.S.makeSignless();
3473 BasicBlock* tmpBB = getBBVal($5);
3474 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3477 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3480 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3481 $6.S.makeSignless();
3482 BasicBlock* tmpBB = getBBVal($6);
3483 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3487 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
3488 $$ = new std::vector<ValueInfo>();
3491 | ValueRefList ',' ResolvedVal {
3496 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
3499 | /*empty*/ { $$ = 0; }
3512 : ArithmeticOps Types ValueRef ',' ValueRef {
3515 const Type* Ty = $2.PAT->get();
3516 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<VectorType>(Ty))
3517 error("Arithmetic operator requires integer, FP, or packed operands");
3518 if (isa<VectorType>(Ty) &&
3519 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3520 error("Remainder not supported on vector types");
3521 // Upgrade the opcode from obsolete versions before we do anything with it.
3522 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3523 Value* val1 = getVal(Ty, $3);
3524 Value* val2 = getVal(Ty, $5);
3525 $$.I = BinaryOperator::create(Opcode, val1, val2);
3527 error("binary operator returned null");
3531 | LogicalOps Types ValueRef ',' ValueRef {
3534 const Type *Ty = $2.PAT->get();
3535 if (!Ty->isInteger()) {
3536 if (!isa<VectorType>(Ty) ||
3537 !cast<VectorType>(Ty)->getElementType()->isInteger())
3538 error("Logical operator requires integral operands");
3540 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3541 Value* tmpVal1 = getVal(Ty, $3);
3542 Value* tmpVal2 = getVal(Ty, $5);
3543 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3545 error("binary operator returned null");
3549 | SetCondOps Types ValueRef ',' ValueRef {
3552 const Type* Ty = $2.PAT->get();
3553 if(isa<VectorType>(Ty))
3554 error("VectorTypes currently not supported in setcc instructions");
3555 unsigned short pred;
3556 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3557 Value* tmpVal1 = getVal(Ty, $3);
3558 Value* tmpVal2 = getVal(Ty, $5);
3559 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3561 error("binary operator returned null");
3562 $$.S.makeUnsigned();
3565 | ICMP IPredicates Types ValueRef ',' ValueRef {
3568 const Type *Ty = $3.PAT->get();
3569 if (isa<VectorType>(Ty))
3570 error("VectorTypes currently not supported in icmp instructions");
3571 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3572 error("icmp requires integer or pointer typed operands");
3573 Value* tmpVal1 = getVal(Ty, $4);
3574 Value* tmpVal2 = getVal(Ty, $6);
3575 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3576 $$.S.makeUnsigned();
3579 | FCMP FPredicates Types ValueRef ',' ValueRef {
3582 const Type *Ty = $3.PAT->get();
3583 if (isa<VectorType>(Ty))
3584 error("VectorTypes currently not supported in fcmp instructions");
3585 else if (!Ty->isFloatingPoint())
3586 error("fcmp instruction requires floating point operands");
3587 Value* tmpVal1 = getVal(Ty, $4);
3588 Value* tmpVal2 = getVal(Ty, $6);
3589 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3590 $$.S.makeUnsigned();
3594 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3595 const Type *Ty = $2.V->getType();
3596 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3598 error("Expected integral type for not instruction");
3599 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3601 error("Could not create a xor instruction");
3604 | ShiftOps ResolvedVal ',' ResolvedVal {
3605 if (!$4.V->getType()->isInteger() ||
3606 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3607 error("Shift amount must be int8");
3608 const Type* Ty = $2.V->getType();
3609 if (!Ty->isInteger())
3610 error("Shift constant expression requires integer operand");
3611 Value* ShiftAmt = 0;
3612 if (cast<IntegerType>(Ty)->getBitWidth() > Type::Int8Ty->getBitWidth())
3613 if (Constant *C = dyn_cast<Constant>($4.V))
3614 ShiftAmt = ConstantExpr::getZExt(C, Ty);
3616 ShiftAmt = new ZExtInst($4.V, Ty, makeNameUnique("shift"), CurBB);
3619 $$.I = BinaryOperator::create(getBinaryOp($1, Ty, $2.S), $2.V, ShiftAmt);
3622 | CastOps ResolvedVal TO Types {
3623 const Type *DstTy = $4.PAT->get();
3624 if (!DstTy->isFirstClassType())
3625 error("cast instruction to a non-primitive type: '" +
3626 DstTy->getDescription() + "'");
3627 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3631 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3632 if (!$2.V->getType()->isInteger() ||
3633 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3634 error("select condition must be bool");
3635 if ($4.V->getType() != $6.V->getType())
3636 error("select value types should match");
3637 $$.I = new SelectInst($2.V, $4.V, $6.V);
3640 | VAARG ResolvedVal ',' Types {
3641 const Type *Ty = $4.PAT->get();
3643 $$.I = new VAArgInst($2.V, Ty);
3647 | VAARG_old ResolvedVal ',' Types {
3648 const Type* ArgTy = $2.V->getType();
3649 const Type* DstTy = $4.PAT->get();
3650 ObsoleteVarArgs = true;
3651 Function* NF = cast<Function>(CurModule.CurrentModule->
3652 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3655 //foo = alloca 1 of t
3659 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3660 CurBB->getInstList().push_back(foo);
3661 CallInst* bar = new CallInst(NF, $2.V);
3662 CurBB->getInstList().push_back(bar);
3663 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3664 $$.I = new VAArgInst(foo, DstTy);
3668 | VANEXT_old ResolvedVal ',' Types {
3669 const Type* ArgTy = $2.V->getType();
3670 const Type* DstTy = $4.PAT->get();
3671 ObsoleteVarArgs = true;
3672 Function* NF = cast<Function>(CurModule.CurrentModule->
3673 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3675 //b = vanext a, t ->
3676 //foo = alloca 1 of t
3679 //tmp = vaarg foo, t
3681 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3682 CurBB->getInstList().push_back(foo);
3683 CallInst* bar = new CallInst(NF, $2.V);
3684 CurBB->getInstList().push_back(bar);
3685 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3686 Instruction* tmp = new VAArgInst(foo, DstTy);
3687 CurBB->getInstList().push_back(tmp);
3688 $$.I = new LoadInst(foo);
3692 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3693 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3694 error("Invalid extractelement operands");
3695 $$.I = new ExtractElementInst($2.V, $4.V);
3696 $$.S.copy($2.S.get(0));
3698 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3699 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3700 error("Invalid insertelement operands");
3701 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3704 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3705 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3706 error("Invalid shufflevector operands");
3707 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3711 const Type *Ty = $2.P->front().first->getType();
3712 if (!Ty->isFirstClassType())
3713 error("PHI node operands must be of first class type");
3714 PHINode *PHI = new PHINode(Ty);
3715 PHI->reserveOperandSpace($2.P->size());
3716 while ($2.P->begin() != $2.P->end()) {
3717 if ($2.P->front().first->getType() != Ty)
3718 error("All elements of a PHI node must be of the same type");
3719 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3724 delete $2.P; // Free the list...
3726 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3727 // Handle the short call syntax
3728 const PointerType *PFTy;
3729 const FunctionType *FTy;
3731 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3732 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3733 // Pull out the types of all of the arguments...
3734 std::vector<const Type*> ParamTypes;
3735 FTySign.makeComposite($3.S);
3737 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3739 ParamTypes.push_back((*I).V->getType());
3744 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3745 if (isVarArg) ParamTypes.pop_back();
3747 const Type *RetTy = $3.PAT->get();
3748 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3749 error("Functions cannot return aggregate types");
3751 // Deal with CSRetCC
3752 ParamAttrsList *PAL = 0;
3753 if ($2 == OldCallingConv::CSRet) {
3754 ParamAttrsVector Attrs;
3755 ParamAttrsWithIndex PAWI;
3756 PAWI.index = 1; PAWI.attrs = ParamAttr::StructRet; // first arg
3757 Attrs.push_back(PAWI);
3758 PAL = ParamAttrsList::get(Attrs);
3761 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg, PAL);
3762 PFTy = PointerType::get(FTy);
3766 // Get the signedness of the result type. $3 is the pointer to the
3767 // function type so we get the 0th element to extract the function type,
3768 // and then the 0th element again to get the result type.
3769 $$.S.copy($3.S.get(0).get(0));
3771 $4.S.makeComposite(FTySign);
3773 // First upgrade any intrinsic calls.
3774 std::vector<Value*> Args;
3776 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3777 Args.push_back((*$6)[i].V);
3778 Instruction *Inst = upgradeIntrinsicCall(FTy->getReturnType(), $4, Args);
3780 // If we got an upgraded intrinsic
3784 // Get the function we're calling
3785 Value *V = getVal(PFTy, $4);
3787 // Check the argument values match
3788 if (!$6) { // Has no arguments?
3789 // Make sure no arguments is a good thing!
3790 if (FTy->getNumParams() != 0)
3791 error("No arguments passed to a function that expects arguments");
3792 } else { // Has arguments?
3793 // Loop through FunctionType's arguments and ensure they are specified
3796 FunctionType::param_iterator I = FTy->param_begin();
3797 FunctionType::param_iterator E = FTy->param_end();
3798 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3800 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3801 if ((*ArgI).V->getType() != *I)
3802 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3803 (*I)->getDescription() + "'");
3805 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3806 error("Invalid number of parameters detected");
3809 // Create the call instruction
3810 CallInst *CI = new CallInst(V, Args.begin(), Args.end());
3811 CI->setTailCall($1);
3812 CI->setCallingConv(upgradeCallingConv($2));
3817 lastCallingConv = OldCallingConv::C;
3825 // IndexList - List of indices for GEP based instructions...
3827 : ',' ValueRefList { $$ = $2; }
3828 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3832 : VOLATILE { $$ = true; }
3833 | /* empty */ { $$ = false; }
3837 : MALLOC Types OptCAlign {
3838 const Type *Ty = $2.PAT->get();
3839 $$.S.makeComposite($2.S);
3840 $$.I = new MallocInst(Ty, 0, $3);
3843 | MALLOC Types ',' UINT ValueRef OptCAlign {
3844 const Type *Ty = $2.PAT->get();
3845 $5.S.makeUnsigned();
3846 $$.S.makeComposite($2.S);
3847 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3850 | ALLOCA Types OptCAlign {
3851 const Type *Ty = $2.PAT->get();
3852 $$.S.makeComposite($2.S);
3853 $$.I = new AllocaInst(Ty, 0, $3);
3856 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3857 const Type *Ty = $2.PAT->get();
3858 $5.S.makeUnsigned();
3859 $$.S.makeComposite($4.S);
3860 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3863 | FREE ResolvedVal {
3864 const Type *PTy = $2.V->getType();
3865 if (!isa<PointerType>(PTy))
3866 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3867 $$.I = new FreeInst($2.V);
3868 $$.S.makeSignless();
3870 | OptVolatile LOAD Types ValueRef {
3871 const Type* Ty = $3.PAT->get();
3873 if (!isa<PointerType>(Ty))
3874 error("Can't load from nonpointer type: " + Ty->getDescription());
3875 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3876 error("Can't load from pointer of non-first-class type: " +
3877 Ty->getDescription());
3878 Value* tmpVal = getVal(Ty, $4);
3879 $$.I = new LoadInst(tmpVal, "", $1);
3880 $$.S.copy($3.S.get(0));
3883 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3885 const PointerType *PTy = dyn_cast<PointerType>($5.PAT->get());
3887 error("Can't store to a nonpointer type: " +
3888 $5.PAT->get()->getDescription());
3889 const Type *ElTy = PTy->getElementType();
3890 Value *StoreVal = $3.V;
3891 Value* tmpVal = getVal(PTy, $6);
3892 if (ElTy != $3.V->getType()) {
3893 StoreVal = handleSRetFuncTypeMerge($3.V, ElTy);
3895 error("Can't store '" + $3.V->getType()->getDescription() +
3896 "' into space of type '" + ElTy->getDescription() + "'");
3898 PTy = PointerType::get(StoreVal->getType());
3899 if (Constant *C = dyn_cast<Constant>(tmpVal))
3900 tmpVal = ConstantExpr::getBitCast(C, PTy);
3902 tmpVal = new BitCastInst(tmpVal, PTy, "upgrd.cast", CurBB);
3905 $$.I = new StoreInst(StoreVal, tmpVal, $1);
3906 $$.S.makeSignless();
3909 | GETELEMENTPTR Types ValueRef IndexList {
3911 const Type* Ty = $2.PAT->get();
3912 if (!isa<PointerType>(Ty))
3913 error("getelementptr insn requires pointer operand");
3915 std::vector<Value*> VIndices;
3916 upgradeGEPInstIndices(Ty, $4, VIndices);
3918 Value* tmpVal = getVal(Ty, $3);
3919 $$.I = new GetElementPtrInst(tmpVal, &VIndices[0], VIndices.size());
3920 ValueInfo VI; VI.V = tmpVal; VI.S.copy($2.S);
3921 $$.S.copy(getElementSign(VI, VIndices));
3929 int yyerror(const char *ErrorMsg) {
3931 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3932 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3933 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3934 if (yychar != YYEMPTY && yychar != 0)
3935 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3937 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3938 std::cout << "llvm-upgrade: parse failed.\n";
3942 void warning(const std::string& ErrorMsg) {
3944 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3945 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3946 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3947 if (yychar != YYEMPTY && yychar != 0)
3948 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3950 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3953 void error(const std::string& ErrorMsg, int LineNo) {
3954 if (LineNo == -1) LineNo = Upgradelineno;
3955 Upgradelineno = LineNo;
3956 yyerror(ErrorMsg.c_str());